only allow children of a specific type in a react component

后端 未结 14 1714
天涯浪人
天涯浪人 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:38

    You can add a prop to your Card component and then check for this prop in your CardGroup component. This is the safest way to achieve this in React.

    This prop can be added as a defaultProp so it's always there.

    class Card extends Component {
    
      static defaultProps = {
        isCard: true,
      }
    
      render() {
        return (
          
    A Card
    ) } } class CardGroup extends Component { render() { for (child in this.props.children) { if (!this.props.children[child].props.isCard){ console.error("Warning CardGroup has a child which isn't a Card component"); } } return (
    {this.props.children}
    ) } }

    Checking for whether the Card component is indeed a Card component by using type or displayName is not safe as it may not work during production use as indicated here: https://github.com/facebook/react/issues/6167#issuecomment-191243709

提交回复
热议问题