[英]Requiring a single React child component in TypeScript (TSX)
If I have an interface that overrides and specifies a single child, something like: 如果我有一个覆盖并指定一个孩子的接口,则类似于:
interface Props extends React.HTMLProps<HTMLDivElement> {
children?: React.ReactElement<any>;
}
class MyComponent extends React.Component<Props, {}> {
// ...
}
IntelliSense correctly shows the single element child prop type, but I can use a component with these props with multiple child components without any errors: IntelliSense可以正确显示单元素子道具类型,但我可以将具有这些道具的组件与多个子组件一起使用,而不会出现任何错误:
<MyComponent>
<div>hello</div>
<div>world</div>
</MyComponent>
This compiles fine with TypeScript 1.8.30.0, but at run time it breaks: 使用TypeScript 1.8.30.0可以很好地进行编译,但是在运行时会中断:
Invariant Violation: ReactDOM.render(): Invalid component element.
It does work with only one <div/>
child element, since the component code is written for that scenario. 它只对一个
<div/>
子元素起作用,因为该组件代码是为该方案编写的。 This seems like a bug to me--I expected it to realize that two <div/>
elements doesn't match the definition of children
. 在我看来,这似乎是个错误-我希望它意识到两个
<div/>
元素与children
的定义不匹配。 I figured I would ask here first, though, before opening an issue, in case I'm missing something. 我想我想先问一下这里,在打开问题之前,以防万一我遗漏了一些东西。
Is it possible to require only a single child via this.props.children
, or must I add a specific prop? 是否可以通过
this.props.children
仅要求一个孩子,或者我必须添加特定的道具?
This worked for me: 这对我有用:
export const Example = (props: { children: ReactElement }) => {
return <div>{props.children}</div>
}
You can find the relevant information below. 您可以在下面找到相关信息。
To quote: 报价:
With React.PropTypes.element you can specify that only a single child can be passed to a component as children.
使用React.PropTypes.element,您可以指定只能将单个子代作为子代传递到组件。
It is possible to enforce only one child. 可能只强制执行一个孩子。
var MyComponent = React.createClass({
propTypes: {
children: React.PropTypes.element.isRequired
},
render: function() {
return (
<div>
{this.props.children} // This must be exactly one element or it will warn.
</div>
);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.