我在控制台中看到了这个错误:
警告:propType失败:提供给
children
的道具ButtonRow
无效。检查BookingForm
的呈现方法。
ButtonRow
看起来像这样:
import React, {Component, PropTypes} from 'react';
export function Left(props) {
return <div className="left-col">{props.children}</div>;
}
export function Right(props) {
return <div className="right-col">{props.children}</div>;
}
const LeftOrRight = PropTypes.oneOfType([Left, Right]);
export default class ButtonRow extends Component {
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(LeftOrRight),
LeftOrRight,
]).isRequired,
};
render() {
console.log(this.props.children);
let children = React.Children.toArray(this.props.children);
return <div className="row">
{children.filter(c => c.type === Left)}
{children.filter(c => c.type === Right)}
</div>
}
}
ButtonRow.Left = Left;
ButtonRow.Right = Right;
我正在渲染它:
<ButtonRow>
<ButtonRow.Left>
xxx
</ButtonRow.Left>
<ButtonRow.Right>
yyy
</ButtonRow.Right>
</ButtonRow>
它的显示与我期望的完全一样。怎么会失败验证?我应该将propTypes
设置为什么?
理想情况下,我想执行以下其中一项:
Left
孩子Right
孩子Left
和一个Right
不应接受其他任何内容
答案 0 :(得分:2)
您可以创建一个自定义可重复使用的道具类型:
export function childrenOf(...types) {
let fieldType = PropTypes.shape({
type: PropTypes.oneOf(types).isRequired,
});
return PropTypes.oneOfType([
fieldType,
PropTypes.arrayOf(fieldType),
]);
}
然后像这样使用它:
export default class RadioMenu extends React.Component {
static propTypes = {
children: WxTypes.childrenOf(RadioButton).isRequired,
};
...
}
答案 1 :(得分:1)
这个答案是正确的https://stackoverflow.com/a/41992473/1426788,但我想与同一问题分享我的经验。
当我的包装器组件呈现单个子而不是多个时,我发生了这个错误:
例如:
<Foo>
<Bar>
</Foo>
会发出警告
<Foo>
<Bar>
<Baz>
</Foo>
不会。
似乎渲染单个子进程的反应遵循不同的语义,然后呈现多个子进程,并且PropTypes应相应地更新。
此处有关可用PropTypes的更多信息:https://facebook.github.io/react/docs/typechecking-with-proptypes.html#proptypes