如何检查 React 中的 parent 中是否存在 child 元素?

How to check if a child element exists in parent in React?

我的组件结构如下:

const Parent = (props) => {
  return <div>{props.children}</div>;
};

const Child1 = (props) => {
  return <h2>child 1</h2>;
};

const Child2 = (props) => {
  return <h2>child 2</h2>;
};

然后我创建了一个实例如下:

const node = <Parent>
  <Child1 />
  <Child2 />
</Parent>

现在,当我将其公开给外界时,用户可能会忘记在 parent 中传递 <Child1 /><Child2 />。我想在 parent 中检测到这一点,然后根据 <Child2 /> 是否通过来渲染其他内容。

我的尝试:我利用上下文 API 在 parent 和 child 之间进行了一些交流。我正在寻找比这更简单的东西。

像这样:https://github.com/mui-org/material-ui/blob/next/packages/mui-lab/src/TimelineItem/TimelineItem.js#L69

如果只有 children 的数量很重要,那么:

  const count = React.Children.count(children);

检查特定组件:

   let child1Exists = false;
let child2Exists = false;
    for (const key in props.children){
       const componentName = props.children[key].type.name
        
       switch(componentName){
         "Child1":
           child1Exists = true;
           break;
         "Child2":
           child2Exists = true;
           break;
         default: break;
        }  
    }
   
    if(child1exists && child2Exists){
      // All good!
    }

最好使用高阶组件使此逻辑可组合。

这是 HOC。你可以在任何地方重复使用它。

function withExpectedChildren(Component, expectedChildren = []) {
  return function Wrapped(props) {
    const hasAllExpectedChildren = expectedChildren.every((expectedChild) =>
      [props.children].flat().find((child) => child.type === expectedChild)
    );
    return hasAllExpectedChildren ? <Component {...props} /> : props.fallback;
  };
}

用上面的 HOC

包装 Parent 组件
const WrappedParent = withExpectedChildren(
  Parent,
  [Child1, Child2]
);

渲染组合组件。 如果有 child 未命中,它会呈现回退。

<WrappedParent fallback={<h2>you missed a child</h2>}>
   <Child1 />
   <Child2 />
</WrappedParent>

您可以在 https://jsfiddle.net/nqbL8g1m/

看到工作 fiddle

就是这个思路,你可以根据自己的需要修改