React - how to determine if a specific child component exists?

前端 未结 2 1208
隐瞒了意图╮
隐瞒了意图╮ 2021-02-10 19:09

If I have this structure:

const MyComponent = (props) => {
    return (
        {props.children}
    );
}

a

2条回答
  •  忘掉有多难
    2021-02-10 19:44

    Given that you want to check that SomeInnerComponent is present as a child or not, you could do the following

    const MyComponent = (props) => {
        for (let child in props.children){
           if (props.children[child].type.displayName === 'SomeInnerComponent'){
              console.log("SomeInnerComponent is present as a child");
            }  
        }
        return (
            {props.children}
        );
    }
    

    Or you could have a propTypes validation on your component

    MyComponent.propTypes: {
        children: function (props, propName, componentName) {
          var error;
          var childProp = props[propName];
          var flag = false;
    
          React.Children.forEach(childProp, function (child) {
            if (child.type.displayName === 'SomeInnerComponent') {
               flag = true
            }
          });
          if(flag === false) {
               error = new Error(componentName + ' does not exist!'
              );
          }
          return error;
        }
      },
    

提交回复
热议问题