8.为什么我们需要使用 React 提供的 Children A

2018-09-03  本文已影响6人  vbuer

props.children并不一定是数组类型,譬如下面这个元素:

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

如果我们使用props.children.map函数来遍历时会受到异常提示,因为在这种情况下props.children是对象(object)而不是数组(array)。React 当且仅当超过一个子元素的情况下会将props.children设置为数组,就像下面这个代码片:

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

这也就是我们优先选择使用React.Children.map函数的原因,其已经将props.children不同类型的情况考虑在内了。

上一篇下一篇

猜你喜欢

热点阅读