only allow children of a specific type in a react component

后端 未结 14 1687
天涯浪人
天涯浪人 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条回答
  •  Happy的楠姐
    2020-11-29 01:45

    For those like me, using the TypeScript version. You can filter/modify components like this:

    this.modifiedChildren = React.Children.map(children, child => {
                if (React.isValidElement(child) && (child as React.ReactElement).type === Card) {
                    let modifiedChild = child as React.ReactElement;
                    // Modifying here
                    return modifiedChild;
                }
                // Returning other components / string.
                // Delete next line in case you dont need them.
                return child;
            });
    

提交回复
热议问题