only allow children of a specific type in a react component

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

    Use the React.Children.forEach method to iterate over the children and use the name property to check the type:

    React.Children.forEach(this.props.children, (child) => {
        if (child.type.name !== Card.name) {
            console.error("Only card components allowed as children.");
        }
    }
    

    I recommend to use Card.name instead of 'Card' string for better maintenance and stability in respect to uglify.

    See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

提交回复
热议问题