如果我将父组件的子组件键入Node
,则表示children
是传递给React.Children.map
的错误类型。但是,如果我将其键入ChildrenArray<any>
,则表示我传递给React.cloneElement
的类型不正确。
import * as React from 'react';
type Props = {
children?: React.ChildrenArray<any>,
};
class Test extends React.Component<Props> {
props: Props;
render() {
return React.Children.map(this.props.children, child =>
React.cloneElement(child, {})
);
}
}
<Test>
<span>foo</span>
<span>bar</span>
</Test>
import * as React from 'react';
type Props = {
children?: Node,
};
class Test extends React.Component<Props> {
props: Props;
render() {
return React.Children.map(this.props.children, child =>
React.cloneElement(child, {})
);
}
}
<Test>
<span>foo</span>
<span>bar</span>
</Test>
答案 0 :(得分:2)
第一个例子的问题是使用React.ChildrenArray<any>
。实际情况并非如此,因为它们必须是React可以理解为节点的元素。如果我将其更改为React.ChildrenArray<*>
到let React infer the allowed type,它似乎工作正常。