检查 React 组件的类型 [英] Check type of React component

查看:28
本文介绍了检查 React 组件的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to loop through component's children and do some things only if child component is of specific type:

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 />');
    }
});

这篇关于检查 React 组件的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆