Javascript 将道具指定为React中的特定组件
我正在写一个组件,我不想成为一个特殊组件的实例Javascript 将道具指定为React中的特定组件,javascript,reactjs,Javascript,Reactjs,我正在写一个组件,我不想成为一个特殊组件的实例 class Component extends React.Component { static propTypes: { children: /*Only ChildComponents allowed*/ } } class ChildComponent extends React.Component {} //应该失败 //应该失败 //应该成功 //应该成功 看这里 更新 由于instanceOf在您的
class Component extends React.Component {
static propTypes: {
children: /*Only ChildComponents allowed*/
}
}
class ChildComponent extends React.Component {}
//应该失败
//应该失败
//应该成功
//应该成功
看这里
更新
由于instanceOf在您的案例中不起作用,请尝试此替代方法-
在propTypes中,允许任何节点-
children: React.PropTypes.node
然后在render
方法中-
React.Children.map(children, (child, index) => {
if (!React.isValidElement(child)
|| !child.type
|| child.type.displayName !== 'ChildComponent'){
// Exterminate! Exterminate!
}
}
不幸的是,这不起作用。PropType.instanceOf使用
instanceOf
运算符,而instanceOf Component
为false
React.Children.map(children, (child, index) => {
if (!React.isValidElement(child)
|| !child.type
|| child.type.displayName !== 'ChildComponent'){
// Exterminate! Exterminate!
}
}