简体   繁体   English

我应该将反应组件渲染为组件数组吗

[英]Should I Render react components as an array of components

I have a simple react component that directly renders several children:我有一个简单的反应组件,直接呈现几个孩子:


return (
<header>
   <img src={logo}/>
   <h1>My Site</h1>
   <nav>...</nav>
</header>
);

Are there drawbacks/benefits of rendering this component as an array of components:将此组件呈现为组件数组是否有缺点/好处:


return (
<header>
   {[
     <img key="1" src={logo}/>,
     <h1  key="2">My Site</h1>,
     <nav key="3">...</nav>
   ]}
</header>
);

Why would you render as an array?为什么要渲染为数组? I see no benefit.我看没有任何好处。 The drawback is that it's confusing to read, best to keep it as close to HTML syntax as possible until you need to introduce JS.缺点是阅读起来比较混乱,最好在需要引入 JS 之前尽量保持接近 HTML 语法。

I don't suggest using an array like that since it impacts readability negatively, and from what I know it does not have any benefits.我不建议使用这样的数组,因为它会对可读性产生负面影响,而且据我所知,它没有任何好处。

I only see this being used when someone is generating components programmatically, like when you're using Array.prototype.map() for example on an array of objects to create a new array of components with props populated from the array of objects.我只看到有人以编程方式生成组件时使用此方法,例如当您在对象数组上使用Array.prototype.map()以创建一个新的组件数组时,其中的道具从对象数组中填充。

You shouldn't use an array for this.您不应该为此使用数组。 if you can create smaller components for whatever inside it can be more beneficial for the redability如果您可以为内部的任何内容创建更小的组件,则对可红色性更有利

If you're thinking in terms of performance, there will probably be some slight drawbacks if you take into consideration the code used to generate the list of elements.如果您从性能方面考虑,如果考虑到用于生成元素列表的代码,可能会有一些轻微的缺点。

But I don't think that would be too much of a concern, what really bothers me, in this case, is the readability since you can write the same code without the brackets and curly braces to make that part a list of components, it's just harder to read and it could confuse someone else working in the same codebase.但我认为这不会引起太大的关注,在这种情况下,真正困扰我的是可读性,因为您可以编写相同的代码而无需括号和花括号,从而使该部分成为组件列表,它是只是更难阅读,并且可能会使在同一代码库中工作的其他人感到困惑。

As an alternative I can think of atm, you can extract that JSX into a component if you need to have it hidden from your render function.作为替代方案,我可以想到 atm,如果您需要将 JSX 从渲染函数中隐藏,您可以将其提取到组件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM