在React中,children
是组合中使用的不透明数据结构。为了对其进行操作,React 公开了 React.Children
API,其中包含方法 React.Children.map
和 React.Children.toArray
>。
根据文档,Children.map
在每个子元素上调用一个函数(通常用于渲染,或 cloneElement
),而 toArray
从不透明的 children
更改为简单的 js 数组。
React.Children.map(child, fn)
和 React.Children.toArray.map(child, fn)
感觉实际上是等效的。我经常看到使用 Children.map
,并且正在寻找确凿的证据来支持最佳实践,或者对 toArray.map
用例的解释。
我的第一直觉是,toArray
显然添加了另一个调用,这可能性能较差(边缘?),但我相信 toArray
也会删除 undefined
或 null
子项。
最佳答案
这是一个非常古老的问题,但我正在添加我发现的内容!
Children.toArray
与 Children.map
有点不同经过时null
或undefined
作为 child 。
<ReactComponent>
<div>one</div>
{ null }
</ReactComponent>
在上面的例子中,
Children.toArray
跳过null
或undefined
和length
结果将是 1
但是Children.map(children, (val) => {})
当 null 时也会迭代,length
结果将是 2
关于javascript - React.Children.map 与 React Children.toArray.map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44721768/