Reactjs 如何遍历组件';打字机里的孩子们有什么反应?
如何在Typescript tsx中迭代React组件的子级 以下是有效的jsx:Reactjs 如何遍历组件';打字机里的孩子们有什么反应?,reactjs,typescript,react-jsx,tsx,Reactjs,Typescript,React Jsx,Tsx,如何在Typescript tsx中迭代React组件的子级 以下是有效的jsx: public render() { return ( <div> {React.Children.map(this.props.children, x => x.props.foo)} </div> ); } public render(){ 返回( {React.Children.map(this.props
public render() {
return (
<div>
{React.Children.map(this.props.children, x => x.props.foo)}
</div>
);
}
public render(){
返回(
{React.Children.map(this.props.Children,x=>x.props.foo)}
);
}
但是,在Typescript中,x的类型是React.ReactElement
,因此我无法访问道具。有什么样的演员我需要做吗
但是,在Typescript中,x的类型是React.ReactElement,因此我无法访问道具。有什么样的演员我需要做吗
对。也更喜欢术语断言
。一个简单的例子:
React.Children.map(this.props.children, x => (x as any).props.foo)
通常应避免使用
any
,因为您会丢失类型信息
在函数参数类型中使用React.ReactElement
:
React.Children.map(this.props.children, (child: React.ReactElement<ChildPropTypes>) => child.props.bar)
React.Children.map(this.props.Children,(child:React.ReactElement)=>child.props.bar)
如果你想要孙子孙女,他们在child.props.children
:)