只允许反应组件中特定类型的子项 [英] only allow children of a specific type in a react component

查看:37
本文介绍了只允许反应组件中特定类型的子项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Card 组件和一个 CardGroup 组件,我想在 CardGroup 的子元素不是't Card 组件.这是可能的,还是我试图解决错误的问题?

I have a Card component and a CardGroup component, and I'd like to throw an error when CardGroup has children that aren't Card components. Is this possible, or am I trying to solve the wrong problem?

推荐答案

您可以为每个孩子使用 displayName,通过类型访问:

You can use the displayName for each child, accessed via type:

for (child in this.props.children){
  if (this.props.children[child].type.displayName != 'Card'){
    console.log("Warning CardGroup has children that aren't Card components");
  }  
}

这篇关于只允许反应组件中特定类型的子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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