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)
使用any为你失去类型信息一般应避免。
而是React.ReactElement<P>在函数参数类型中使用:
React.Children.map(this.props.children, (child: React.ReactElement<ChildPropTypes>) => child.props.bar)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11224 次 |
| 最近记录: |