Javascript 直接使用children道具和使用React.children.toArray方法的区别
我在玩Javascript 直接使用children道具和使用React.children.toArray方法的区别,javascript,reactjs,Javascript,Reactjs,我在玩React.Children和Children属性,我发现使用Children.filter()和使用React.Children.toArray(Children)没有区别.filter通过直接使用子道具的索引,我还可以从子道具中渲染特定的子道具,并将其视为普通数组 所以我想知道这两种方法之间有什么区别吗?如果我可以直接将道具与arrays方法结合使用,那么react团队首先为什么要实现toString()方法呢 我尝试了console.log()这两种方法,我认为这两种方法没有区别 c
React.Children
和Children
属性,我发现使用Children.filter()
和使用React.Children.toArray(Children)没有区别.filter
通过直接使用子道具的索引,我还可以从子道具中渲染特定的子道具,并将其视为普通数组
所以我想知道这两种方法之间有什么区别吗?如果我可以直接将道具与arrays方法结合使用,那么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>
);
}
const ChildrenContainer=(道具)=>{
const{children,howMany}=props;
console.log(children,'\n',children.toArray(children));
返回(
{Children.map(Children,(thisArg)=>thisArg)}
);
}
如果你看看这里的文档:你会注意到一些事情
React.Children
处理null
和未定义的。如果子项为null或未定义,则调用children.filter()
将出错
子对象.only()
,它们提供了比常规数组更多的特定于react的功能toArray()
更改键以保留嵌套数组的语义因此,在您的特定情况下,您可能不会注意到任何差异。但是,即使您确信
子对象
始终是一个可用的数组,使用React.children
仍然是一个很好的实践。这是因为它抽象出了子概念,这样您的代码就更能适应未来的需要(对于代码的更改,以及可能的更改本身的反应).我不明白它怎么可能子项可以为null或未定义,即使它是根据我们传递给它的内容构造的。您能进一步解释一下toArray()
在这里的语义意味着什么吗正如文档所说,每个键在返回数组之前都有前缀。这就是说,假设您有嵌套的子项,它们的键将保持唯一性(否则它们可能不会是唯一的)。