检查React组件的类型

时间:2019-04-17 14:11:29

标签: reactjs

我需要遍历组件的children并仅在子组件为特定类型时才做一些事情:

React.Children.forEach(this.props.children, child => {
    if (...) {
        console.log('Suitable component!');
    }
});

4 个答案:

答案 0 :(得分:4)

正如康斯坦丁·斯莫拉宁(Konstantin Smolyanin)所指出的那样,公认的答案可能与react-hot-loader不太匹配。

希望更安全的替代方法,建议here

import MyComponent from './MyComponent';
const myComponentType = (<MyComponent />).type;

this.props.children.forEach(child => {
    if (child.type === myComponentType ) {
        console.log('This child is <MyComponent />');
    }
});

答案 1 :(得分:2)

其他解决方案:

import MyComponent from './MyComponent';
// const myComponentType = (<MyComponent />).type;
// It's the same than
const myComponentType = React.createElement(MyComponent).type;

this.props.children.forEach(child => {
    if (child.type === myComponentType) {
        console.log('This child is <MyComponent />');
    }
});

答案 2 :(得分:1)

这是您应该做的:

import MyComponent from './MyComponent';

this.props.children.forEach(child => {
    if (child.type === MyComponent) {
        console.log('This child is <MyComponent />');
    }
});

答案 3 :(得分:0)

我当前的解决方案是

import MyComponent from 'MyComponent';

...


React.Children.forEach(this.props.children, child => {
    if (child.type.name === MyComponent.name) {
        console.log('Suitable component!');
    }
});

但是我看到React元素的type属性没有记录(或者我在阅读文档时不好?)。因此,我正在寻找更可靠的解决方案。

更新

实际上,代码if (child.type.name === MyComponent.name)应该简化为if (child.type === MyComponent)。但这对我没有用。我发现这是由react-hot-loader引起的。禁用它可以修复我的应用。

react-hot-loader GitHub上的相关问题:https://github.com/gaearon/react-hot-loader/issues/304