我需要遍历组件children
并仅在子组件是特定类型时才执行某些操作:
React.Children.forEach(this.props.children, child => {
if (...) {
console.log('Suitable component!');
}
});
我需要遍历组件children
并仅在子组件是特定类型时才执行某些操作:
React.Children.forEach(this.props.children, child => {
if (...) {
console.log('Suitable component!');
}
});
这是你应该做的:
import MyComponent from './MyComponent';
this.props.children.forEach(child => {
if (child.type === MyComponent) {
console.log('This child is <MyComponent />');
}
});
正如康斯坦丁·斯莫利亚宁 (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 />');
}
});
其他解决方案:
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 />');
}
});
我目前的解决方案是
import MyComponent from 'MyComponent';
...
React.Children.forEach(this.props.children, child => {
if (child.type.name === MyComponent.name) {
console.log('Suitable component!');
}
});
但我看到type
React 元素的属性没有记录(或者我不擅长阅读文档?)。所以我正在寻找更可靠的解决方案。
更新:
实际上代码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