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!
  }
}