reactjs React.Children.map与children.map有什么区别?

cvxl0en2  于 2023-08-04  发布在  React
关注(0)|答案(3)|浏览(110)

在React v16.2.0中,有一个新的API调用React.Children
我很好奇React.Children和直接使用children有什么不同。
例如,如果我想操纵子内容,我可以在两种方法中都做到这一点。example

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的目的是什么?

ivqmmu1c

ivqmmu1c1#

React组件的子组件是一个节点,可能是undefined或null。React.Children.map是一个实用程序功能,可以帮助您处理不同的情况。
React.Children.map
对children中包含的每个直接子级调用函数,并将此设置为thisArg。如果children是一个数组,它将被遍历,并为数组中的每个child调用该函数。如果children为null或undefined,则此方法将返回null或undefined,而不是数组。
您应始终使用React.Children.map来遍历应用中的子项。使用children.map在children不是数组时抛出错误。

wj8zmpe1

wj8zmpe12#

请看一下这个例子,看看不同的
粘贴到控制台浏览器:

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的情况

g9icjywg

g9icjywg3#

据我所知,对于你们的业务来说,没有真实的的区别。但是,React.Children提供了处理this.props.children的实用程序。对于map的使用,我认为文档中有一条注解可能会很有趣:
如果children是一个带键的片段或数组,则将遍历它
因此,它们的实现似乎比你刚刚使用Array.prototype.map做得多一点。
您可以阅读React.Children提供的其他功能,但它们似乎提供了方便的功能,因此您不必担心遍历可能有孩子的孩子等等。

相关问题