检查 React 组件是否为空或没有子组件

Check if React component is empty or has no child component

如何检查 React 组件是否为空或没有子组件?例如,如果我有一个名为组件 A 的组件,我如何检查它是否包含组件 B?

您可以使用 this.props.children 获取任何子组件。如果只有一个子组件,this.props.children 将指向该子组件,否则它将 return 一个子组件数组。

如果它是一个数组,你可以使用this.props.children.map循环遍历它们,你可以找到组件的名称或类型,如下所示:

this.props.children.map(child => console.log(child.type))