【问题标题】:How to iterate through a Component's Children in Typescript React?如何在 Typescript React 中遍历组件的子项?
【发布时间】:2016-03-05 23:04:41
【问题描述】:

如何在 Typescript tsx 中遍历 React 组件的子组件?

以下是有效的 jsx:

public render() {
    return (
        <div>
            {React.Children.map(this.props.children, x => x.props.foo)}
        </div>
    );
}

但是,在 Typescript 中,x 的类型是 React.ReactElement&lt;any&gt;,所以我无法访问 props。我需要做某种类型的演员吗?

【问题讨论】:

    标签: reactjs typescript react-jsx tsx


    【解决方案1】:

    但是,在 Typescript 中,x 的类型是 React.ReactElement,所以我无法访问 props。我需要做某种类型的演员吗?

    是的。也更喜欢术语assertion。一个快速的:

    React.Children.map(this.props.children, x => (x as any).props.foo)
    

    【讨论】:

      【解决方案2】:

      通常应避免使用any,因为您会丢失类型信息。

      在函数参数类型中改用React.ReactElement&lt;P&gt;

      React.Children.map(this.props.children, (child: React.ReactElement<ChildPropTypes>) => child.props.bar)
      

      【讨论】:

      • 如果你想要孙子,他们在child.props.children :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2019-07-09
      • 2022-01-04
      相关资源
      最近更新 更多