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

a 夏天 提交于 2019-12-21 02:47:47

问题


If I have this structure:

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

and I use it like this:

<MyComponent>
    <SomeInnerComponent />
</MyComponent>

How can I check to see if <SomeInnerComponent /> has specifically been included between <MyComponent></MyComponent>, from within the MyComponent function?


回答1:


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 (
        <Wrapper />{props.children}</Wrapper>
    );
}

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;
    }
  },



回答2:


Just want to provide an answer for a similar but different need, where you might have an HOC wrapping several layers of components, and you'd like to see if the HOC has already wrapped a component. The method I came up with was to have the HOC add a data-attribute onto the component to serve as a flag, which the HOC could then check on subsequent runs.

const WithFoo = Component = props => {
  return props["data-with-foo"]
    ? <Component {...props} />
    : (
      <FooWrapper>
        <Component {...props} data-with-foo />
      </FooWrapper>
    );
};


来源:https://stackoverflow.com/questions/45209760/react-how-to-determine-if-a-specific-child-component-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!