循环这个.props.children我如何测试他们的类型

Looping this.props.children how do I test their type?

本文关键字:测试 类型 他们的 何测试 props children 循环      更新时间:2023-09-26

在自定义 React 组件的以下代码片段中

React.Children.map(this.props.children), (child) => {
    if (predicate(child)) {
        // do stuff
    }
    else {
        // do other stuff
    }
}

predicate是一个测试子属性或其他属性的函数。 如何编写predicate来测试子元素是什么类型的元素?

在文章中, 在 React 中向孩子发送道具,你会看到我上面应用的相同模式,除了他的谓词函数看起来像child.type === RadioOption.type——如果我想检查孩子继承的类型,这不起作用。

就我而言,我有StatelessModal - child可能是扩展StatelessModal的几个不同组件之一。

当我知道孩子是扩展无状态模式的模态组件之一时,我发现predicate = (child) => child instanceof StatelessModalpredicate = (child) => child.type instanceof StatelessModal都不起作用。

我在控制台上玩了一圈,发现这是有效的:

predicate = (child) => child.type.prototype instanceof StatelessModal

虽然ReactElementtype属性似乎没有记录,但可以合理地注意到,在这里,child是一个ReactElement,而child.type是一个ComponentClass(你可能还会发现它可能是一个stringStatelessComponent)——ComponentClass 是定义组件的类;如果组件是通过继承创建的, 类原型链包括继承的类型,由instanceof揭示

接受的答案对我根本不起作用。

我已经测试了几种检查儿童类型的方法。结论是:

predicate = (child) => child.type === StatelessModal

开发和生产环境中为 react@16.7 和 react@16.8 中的类组件和功能组件工作。

https://github.com/dancerphil/react-children-type 中的更多测试用例

https://dancerphil.github.io/react-children-type/显示了生产构建的结论。