React.Children.map 与 children.map,有什么不同?

IT技术 javascript reactjs
2021-05-15 03:15:39

React v16.2.0 中,有一个新的 API 调用React.Children

我很好奇React.Childrenchildren直接使用有什么不同

例如,如果我想操纵子内容,我可以在这两种方法中都做到这一点。例子

const Child = () => (
  <div>child</div>
)

class App extends React.Component {
  render() {
    const template1 = React.Children.map(this.props.children, (child) => {
      return React.cloneElement(child);
    });

    const template2 = this.props.children.map((child) => {
      return React.cloneElement(child);
    });
    return [template1, template2];
  }
}

结果是一样的。

有谁知道有什么不同?

或者react团队发布这个API的目的是什么。

谢谢你。

3个回答

React 组件的子节点是一个可能未定义或为空的节点。React.Children.map 是一个实用函数,可以帮助您处理不同的情况。

react.Children.map

使用 this 设置为 thisArg 对包含在子节点中的每个直接子节点调用一个函数。如果 children 是一个数组,它将被遍历,并且将为数组中的每个孩子调用该函数。如果 children 为 null 或 undefined,则此方法将返回 null 或 undefined 而不是数组。

您应该始终使用 React.Children.map 来遍历应用程序中的子项。当 children 不是数组时,使用 children.map 会抛出错误。

请看一下这个例子,看看不同的

将此粘贴到控制台浏览器:

var children = null
chidren.map(i => {return i}) // => VM370:1 Uncaught TypeError: Cannot read property 'map' of null
React.Children.map(children, i => {return i;}) // return null

这是结果:结果

所以 React.Children.map 会处理 children 为 null 或 undefined 的情况

据我所知,对于您的操作,没有真正的区别。但是,React.Children提供了用于处理this.props.children. 对于使用,我认为文档map有一条评论可能很有趣:

如果 children 是键控片段或数组,它将被遍历

所以他们的实现似乎比你刚刚使用的Array.prototype.map.

您可以阅读其他功能React.Children提供的内容,但在很大程度上似乎它们提供了便利功能,因此您不必担心遍历可能有孩子的孩子等等。