only allow children of a specific type in a react component

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

    static propTypes = {
    
      children : (props, propName, componentName) => {
                  const prop = props[propName];
                  return React.Children
                           .toArray(prop)
                           .find(child => child.type !== Card) && new Error(`${componentName} only accepts "" elements`);
      },
    
    }
    

提交回复
热议问题