only allow children of a specific type in a react component

后端 未结 14 1651
天涯浪人
天涯浪人 2020-11-29 00:59

I have a Card component and a CardGroup component, and I\'d like to throw an error when CardGroup has children that aren\'t Card

相关标签:
14条回答
  • 2020-11-29 01:47

    I published the package that allows to validate the types of React elements https://www.npmjs.com/package/react-element-proptypes :

    const ElementPropTypes = require('react-element-proptypes');
    
    const Modal = ({ header, items }) => (
        <div>
            <div>{header}</div>
            <div>{items}</div>
        </div>
    );
    
    Modal.propTypes = {
        header: ElementPropTypes.elementOfType(Header).isRequired,
        items: React.PropTypes.arrayOf(ElementPropTypes.elementOfType(Item))
    };
    
    // render Modal 
    React.render(
        <Modal
           header={<Header title="This is modal" />}
           items={[
               <Item/>,
               <Item/>,
               <Item/>
           ]}
        />,
        rootElement
    );
    
    0 讨论(0)
  • 2020-11-29 01:51

    You can use the displayName for each child, accessed via type:

    for (child in this.props.children){
      if (this.props.children[child].type.displayName != 'Card'){
        console.log("Warning CardGroup has children that aren't Card components");
      }  
    }
    
    0 讨论(0)
提交回复
热议问题