only allow children of a specific type in a react component

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

    I made a custom PropType for this that I call equalTo. You can use it like this...

    class MyChildComponent extends React.Component { ... }
    
    class MyParentComponent extends React.Component {
      static propTypes = {
        children: PropTypes.arrayOf(PropTypes.equalTo(MyChildComponent))
      }
    }
    

    Now, MyParentComponent only accepts children that are MyChildComponent. You can check for html elements like this...

    PropTypes.equalTo('h1')
    PropTypes.equalTo('div')
    PropTypes.equalTo('img')
    ...
    

    Here is the implementation...

    React.PropTypes.equalTo = function (component) {
      return function validate(propValue, key, componentName, location, propFullName) {
        const prop = propValue[key]
        if (prop.type !== component) {
          return new Error(
            'Invalid prop `' + propFullName + '` supplied to' +
            ' `' + componentName + '`. Validation failed.'
          );
        }
      };
    }
    

    You could easily extend this to accept one of many possible types. Maybe something like...

    React.PropTypes.equalToOneOf = function (arrayOfAcceptedComponents) {
    ...
    }
    

提交回复
热议问题