在React中,children是组合中使用的不透明数据结构。为了实现这一点,React公开了React.Children应用程序接口,其中包含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的子调用。
发布于 2021-02-04 17:08:42
这是一个非常古老的问题,但我正在添加我发现的内容!
当将null或undefined作为子级传递时,Children.toArray与Children.map略有不同。
<ReactComponent>
<div>one</div>
{ null }
</ReactComponent>在上面的示例中,
Children.toArray跳过null或undefined,结果的length将为1
但是,当结果为null时,Children.map(children, (val) => {})也会迭代,结果的length将为2
发布于 2017-06-23 22:41:13
根据the react code的说法,Children.toArray与传递身份函数(x) => x的Children.map相同。因此,与调用Children.toArray(children).map(func)相比,Children.map(children, func)的性能更高。
发布于 2021-07-20 12:48:10
如果您使用的是Inline If with Logical && Operator,则React.Children.map和React.Children.toArray.map之间的这种区别非常重要
假设您有这个React组件
const ReactComponent = () => {
return (
React.Children.map((child, index) => (
<div>{child}</div>
))
)
}
const checkBooleanValue() => {
return false;
}在以下情况下,您可以将其与子级和条件一起使用:
<ReactComponent>
<span>Child</span>
{checkBooleanValue() &&
<span>Another Child</span>
}
</ReactComponent>如果checkBooleanValue()为false
React.Children.map将为您提供用于内联If的
<span> 的两个子项React.Children.toArray.map只会给你一个孩子:<span> React.Element的
使用React.Children.map,你最终会得到第二个孩子的一个空的div。
https://stackoverflow.com/questions/44721768
复制相似问题