only allow children of a specific type in a react component

后端 未结 14 1680
天涯浪人
天涯浪人 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 use a custom propType function to validate children, since children are just props. I also wrote an article on this, if you want more details.

    var CardGroup = React.createClass({
      propTypes: {
        children: function (props, propName, componentName) {
          var error;
          var prop = props[propName];
    
          React.Children.forEach(prop, function (child) {
            if (child.type.displayName !== 'Card') {
              error = new Error(
                '`' + componentName + '` only accepts children of type `Card`.'
              );
            }
          });
    
          return error;
        }
      },
    
      render: function () {
        return (
          
    {this.props.children}
    ); } });

提交回复
热议问题