检查React组件的类型

Kon*_*nin 2 reactjs

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

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

Ert*_*ani 6

这是您应该做的:

import MyComponent from './MyComponent';

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

  • 我发现问题了!如此奇怪的行为是由我在开发模式下使用的“react-hot-loader”引起的。 (4认同)

leo*_*loy 5

正如康斯坦丁·斯莫利亚宁 (Konstantin Smolyanin) 所指出的,接受的答案可能与 react-hot-loader 配合得不好。

一个希望更安全的选择,这里建议:

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

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


小智 5

其他解决方案:

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 />');
    }
});
Run Code Online (Sandbox Code Playgroud)