给定一个呈现其子级的简单组件:
class ContainerComponent extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default ContainerComponent;
问题:children prop 的 propType 应该是什么?
当我将它设置为对象时,当我使用具有多个子项的组件时它会失败:
<ContainerComponent>
<div>1</div>
<div>2</div>
</ContainerComponent>
Warning: Failed prop type: Invalid prop
children
of typearray
supplied toContainerComponent
, expectedobject
.
如果我将它设置为一个数组,如果我只给它一个孩子,它将失败,即:
<ContainerComponent>
<div>1</div>
</ContainerComponent>
警告:道具类型失败:提供给 ContainerComponent 的类型对象的无效道具子项,预期数组。
请告知,我是否应该不费心检查子元素的 propTypes ?
原文由 d3ming 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
oneOfType
或PropTypes.node
尝试这样的事情或者