如何在 React Typescript 中迭代组件的子组件

发布日期:2026-07-15 11:09:04   来源 : 杭州电子商务研究院    浏览量 :9
杭州电子商务研究院 发布日期:2026-07-15 11:09:04  
9

介绍

React 不附带开箱即用的类型检查系统。在开发复杂或庞大的企业级应用程序时,您可能希望编写更好的代码,以便轻松进行单元测试、类型检查和调试。TypeScript 是 JavaScript 的编译超集,可以做到这一点。

在本指南中,您将快速了解如何将 TypeScript 与 React 结合使用,并学习如何在 React 组件内强制类型检查。

使用 TypeScript 类型检查创建组件

首先创建主要的App组件。

      class App extends React.Component<{}, AppState> {
  //...
}
    

在此示例中,您将从端点获取用户列表并将其显示在前端。要对用户实体进行类型检查,请User.interface.tsx文件中创建一个名为User 的接口。

      export default interface User {
  id: number;
  name: string;
  avatar: string;
}
    

接下来,创建一个AppState接口来对App组件中的状态进行类型检查

tsconfig文件中添加“allowSyntheticDefaultImports”:true行以使用类似于常规 jsx 的导入语句。

      import React from "react";

import UserInterface from "User.interface.tsx";

interface AppState {
  users: UserInterface[];
}

class App extends React.Component<{}, AppState> {
  constructor(props: any) {
    super(props);

    this.state = {
      users: [],
    };
  }

  render() {
    // ...
  }
}
    

要在网页上呈现单个用户,请创建一个用户组件。

      import React, { Component } from "react";

import UserInterface from "../User.interface.tsx";

const User = ({ id, name, avatar }: UserInterface) => (
  <div className="user-container" data-id={id}>
    <img src={avatar} className="user-avatar" />
    <span className="user-name">{name}</span>
  </div>
);

export default User;
    

获取数据并分配状态

componentDidMount生命周期方法中,使用浏览器的 Fetch API 从后端服务器获取用户列表。如下所示,将用户的实体 URL 传递给fetch方法,一旦 JSON 响应可供使用,就将用户设置为状态。

      class App extends React.Component<{}, AppState> {
  constructor(props: any) {
    super(props);

    this.state = {
      users: [],
    };
  }

  componentDidMount() {
    const URL = `some-user-endpoint-for-fetching-users`; // in a real world example this would be a valid URL
    fetch(URL)
      .then((res) => res.json())
      .then((data) =>
        this.setState({
          users: data.users,
        })
      );
  }

  render() {
    // ...
  }
}
    

使用 Map 迭代用户的状态

map方法可用于迭代数组。要利用类型检查,请使用 UserInterface用户数组中的每个子项进行类型检查

      // ...

import User from "./components/User";

class App extends React.Component<{}, AppState> {
  constructor(props: any) {
    super(props);

    this.state = {
      users: [],
    };
  }

  componentDidMount() {
    const URL = `some-user-endpoint-for-fetching-users`;
    fetch(URL)
      .then((res) => res.json())
      .then((data) =>
        this.setState({
          users: data.users,
        })
      );
  }

  render() {
    return (
      <div className="users">
        {this.state.users.map((user: UserInterface) => (
          <User {...user} />
        ))}
      </div>
    );
  }
}
    

以下是分配道具的简写版本。

      <User {...user} />
    

上述语法推断如下。

      <User id={user.id} name={user.name} avatar={user.avatar} />
    

遍历组件的子项

遍历组件的子组件与任何其他数组相同。在这种情况下,也使用map方法。要对子组件进行类型检查,请使用React.ReactElement类型,以及子组件 props 的类型。在本例中,它是UserInterface

      import React from "react";
import UserInterface from "User.interface.tsx";

interface AppProps {
  children: React.ReactElement<UserInterface>[];
}

class App extends React.Component<AppProps, {}> {
  render() {
    return this.props.children.map(
      (child: React.ReactElement<UserInterface>) => (
        <div>{child.props.name}</div>
      )
    );
  }
}
    

结论

TypeScript 是一款出色的实用程序,可用于创建经过类型检查的代码库。这将有助于调试进一步的问题,并在应用程序开发生命周期中节省大量解决运行时错误的时间。要迭代数组,请使用 map forEach reduce filter方法;每种方法都有不同的用途。要从外部源获取数据,您也可以使用 Axios。

这就是本指南的全部内容。继续学习。

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据