为什么用React.Children.map(props.children, () => )而不是props.children.map(() => )


不能保证props.children将是一个数组。

以此代码为例,

<Parent>
  <h1>Welcome.</h1>
</Parent>

 

如果我们尝试使用props.children.map它来映射孩子,父母内部会抛出错误,因为它props.children是一个对象而不是一个数组。

props.children如果有多个子元素(如此),则React只会生成一个数组

<Parent>
  <h1>Welcome.</h1>
  <h2>props.children will now be an array</h2>
</Parent>

 

这就是为什么你想要赞成,React.Children.map因为它的实现考虑到props.children可能是一个数组或一个对象。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM