如何在 Typescript React 中遍历组件的子级?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34030328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate through a Component's Children in Typescript React?
提问by CookieOfFortune
How do I iterate through a React component's children in Typescript tsx?
如何在 Typescript tsx 中遍历 React 组件的子级?
The following would be valid jsx:
以下将是有效的 jsx:
public render() {
return (
<div>
{React.Children.map(this.props.children, x => x.props.foo)}
</div>
);
}
However, in Typescript, the type of x is React.ReactElement<any>
so I have no access to props. Is there some kind of casting that I need to do?
但是,在 Typescript 中,x 的类型是React.ReactElement<any>
这样的,因此我无法访问道具。有什么我需要做的演员吗?
采纳答案by Ian Chadwick
Using any
should generally be avoided as you're losing the type info.
使用any
为你失去类型信息一般应避免。
Instead use React.ReactElement<P>
in the function parameter type:
而是React.ReactElement<P>
在函数参数类型中使用:
React.Children.map(this.props.children, (child: React.ReactElement<ChildPropTypes>) => child.props.bar)
回答by basarat
However, in Typescript, the type of x is React.ReactElement so I have no access to props. Is there some kind of casting that I need to do?
但是,在 Typescript 中, x 的类型是 React.ReactElement 所以我无法访问 props。有什么我需要做的演员吗?
Yes. Also prefer the term assertion
. A quick one:
是的。也更喜欢这个词assertion
。一个快速的:
React.Children.map(this.props.children, x => (x as any).props.foo)