如何在Typescript React中遍历Component的Children?

Coo*_*une 12 typescript reactjs react-jsx tsx

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

以下是有效的jsx:

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

但是,在Typescript中,x的类型是React.ReactElement<any>这样我无法访问props.我需要做某种铸造吗?

bas*_*rat 16

但是,在Typescript中,x的类型是React.ReactElement,因此我无法访问props.我需要做某种铸造吗?

是.也喜欢这个词assertion.一个快速的:

React.Children.map(this.props.children, x => (x as any).props.foo)
Run Code Online (Sandbox Code Playgroud)


Ian*_*ick 5

使用any为你失去类型信息一般应避免。

而是React.ReactElement<P>在函数参数类型中使用:

React.Children.map(this.props.children, (child: React.ReactElement<ChildPropTypes>) => child.props.bar)
Run Code Online (Sandbox Code Playgroud)

  • 如果你想要孙子,他们在`child.props.children` :) (3认同)