only allow children of a specific type in a react component

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

    For me the simplest way to achieve this was following code.

    Example 1:

    import React, {Children} from 'react';
    
    function myComponent({children}) {
    
      return (
        
    {children && Children.map(children, child => { if (child.type === 'div') return child })}
    ) } export default myComponent;

    Example 2 - With Component

    import React, {Children} from 'react';
    
    function myComponent({children}) {
    
      return (
        
    {children && Children.map(children, child => { if (child.type.displayName === 'Card') return child })}
    ) } export default myComponent;

提交回复
热议问题