在自定义 React 组件中的以下代码片段中
React.Children.map(this.props.children), (child) => {
if (predicate(child)) {
// do stuff
}
else {
// do other stuff
}
}
predicate
是一个测试孩子的某些属性或其他什么的函数。我怎样才能写predicate
测试孩子是什么类型的元素?
在文章中,在 React 中将 Pros 发送给孩子 http://jaketrent.com/post/send-props-to-children-react/你会看到我上面应用的相同模式,除了他的谓词函数看起来像child.type === RadioOption.type
-- 如果我想检查孩子继承的类型,这不起作用。
就我而言,我有StatelessModal
-- child
可能是扩展的几个不同组件之一StatelessModal
.
当我知道 child 是扩展 StatelessModal 的 Modal 组件之一时,我发现两者都不是predicate = (child) => child instanceof StatelessModal
nor predicate = (child) => child.type instanceof StatelessModal
work.
我在控制台中玩了一下并发现这是有效的:
predicate = (child) => child.type.prototype instanceof StatelessModal
虽然type
的财产ReactElement
似乎没有记录,这里有理由注意,child
is a ReactElement
, and child.type
is a ComponentClass
(您可能还会发现它可能是string
or StatelessComponent
) -- ComponentClass 是定义组件的类;如果组件是通过继承创建的,则类原型链包括继承的类型,该类型通过以下方式显示instanceof https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)