我需要遍历组件的children并且仅在子组件为特定类型时才做一些事情:
React.Children.forEach(this.props.children, child => {
if (...) {
console.log('Suitable component!');
}
});
Run Code Online (Sandbox Code Playgroud)
这是您应该做的:
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)
正如康斯坦丁·斯莫利亚宁 (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)
| 归档时间: |
|
| 查看次数: |
2528 次 |
| 最近记录: |