直接使用children prop和使用React.Children.toArray方法的区别

A. *_*aal 4 javascript reactjs

我正在玩React.Childrenand属性,我发现 using和 usingchildren之间没有区别,我还可以通过直接使用它的索引从孩子道具中渲染特定的孩子并将其视为普通数组children.filter()React.Children.toArray(children).filter

所以我想知道这两种方法有什么区别吗?如果我可以直接将 props 与数组方法一起使用,那么为什么 React 团队toString()首先要实现该方法

我尝试了 console.log() 这两个方法,我发现这两种方法之间没有区别

const ChildrenContainer = (props) => {
  const { children, howMany } = props;
  console.log(children, '\n', Children.toArray(children));
  return (
    <div className="card-columns">
      {Children.map(children, (thisArg) => thisArg)}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*Way 5

如果您查看此处的文档: https: //reactjs.org/docs/react-api.html#reactchildren您会注意到一些事情。

  1. React.Children处理nullundefined。如果children为空或未定义,调用children.filter()将会出错。

  2. 它涉及<Fragment>儿童

  3. 包括辅助函数,例如.only()提供比常规数组更多的 React 特定功能。

  4. toArray()更改键以保留嵌套数组的语义。

因此,在您的具体情况下,您可能不会注意到任何差异。但即使您确定它children始终是一个可用的数组,使用 仍然是一个很好的做法React.children。这是因为它抽象了子概念,以便您的代码更加面向未来(对于代码的更改以及对自身做出反应的潜在更改)。