javascript - React.Children.map 与 React Children.toArray.map

标签 javascript reactjs

在React中,children是组合中使用的不透明数据结构。为了对其进行操作,React 公开了 React.Children API,其中包含方法 React.Children.mapReact.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 也会删除 undefinednull 子项。

最佳答案

这是一个非常古老的问题,但我正在添加我发现的内容!

Children.toArrayChildren.map 有点不同经过时nullundefined作为 child 。

<ReactComponent>
  <div>one</div>
  { null }
</ReactComponent>

在上面的例子中,

Children.toArray跳过nullundefinedlength结果将是 1

但是Children.map(children, (val) => {})当 null 时也会迭代,length结果将是 2

关于javascript - React.Children.map 与 React Children.toArray.map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44721768/

相关文章:

php - 将 php 变量传递给 xmlhttp.responseText

javascript - 错误 : Cannot find module 'html-webpack-plugin' - Webpack (React)

javascript - AJAX加载包含ReactJS对象的php

javascript - 将 Flow 用于样式化组件 Props

javascript - 如何更改 React 应用程序中静态资源的缓存策略(使用 create-react-app 创建)

javascript - Uncaught Error : DOM element with id x in Element cache is not same as element in DOM

javascript - 使用 Vue CLI 在 Node js 上进行 Express session

javascript - ID Workbench 使用 JAVASCRIPT 从 DITA 生成 XHTML

reactjs - Jest/Enzyme document.createRange 不是挂载函数

html - 另一个 div 内的 div 的边界半径重叠