美文网首页
8.为什么我们需要使用 React 提供的 Children A

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

作者: vbuer | 来源:发表于2018-09-03 14:24 被阅读6次

    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不同类型的情况考虑在内了。

    相关文章

      网友评论

          本文标题:8.为什么我们需要使用 React 提供的 Children A

          本文链接:https://www.haomeiwen.com/subject/ixbwiftx.html