only allow children of a specific type in a react component

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

    Considered multiple proposed approaches, but they all turned out to be either unreliable or overcomplicated to serve as a boilerplate. Settled on the following implementation.

    class Card extends Component {
      // ...
    }
    
    class CardGroup extends Component {
      static propTypes = {
        children: PropTypes.arrayOf(
          (propValue, key, componentName) => (propValue[key].type !== Card)
            ? new Error(`${componentName} only accepts children of type ${Card.name}.`)
            : null
        )
      }
      // ...
    }
    

    Here're the key ideas:

    1. Utilize the built-in PropTypes.arrayOf() instead of looping over children
    2. Check the child type via propValue[key].type !== Card in a custom validator
    3. Use variable substitution ${Card.name} to not hard-code the type name

    Library react-element-proptypes implements this in ElementPropTypes.elementOfType():

    import ElementPropTypes from "react-element-proptypes";
    
    class CardGroup extends Component {
      static propTypes = {
        children: PropTypes.arrayOf(ElementPropTypes.elementOfType(Card))
      }
      // ...
    }
    

提交回复
热议问题