React-如何确定特定的子组件是否存在? [英] React - how to determine if a specific child component exists?

查看:365
本文介绍了React-如何确定特定的子组件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我具有以下结构:

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

我这样使用它:

<MyComponent>
    <SomeInnerComponent />
</MyComponent>

如何检查< SomeInnerComponent /> 特别包含在 MyComponent 中的< MyComponent>< / MyComponent> 之间

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

推荐答案

鉴于您要检查是否存在 SomeInnerComponent 无论您是不是孩子,都可以执行以下操作

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

或者您可以在组件上进行propTypes验证

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

这篇关于React-如何确定特定的子组件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆