在 React JSX 中循环 [英] Loop inside React JSX

查看:32
本文介绍了在 React JSX 中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 React JSX 中执行以下操作(其中 ObjectRow 是一个单独的组件):

I'm trying to do something like the following in React JSX (where ObjectRow is a separate component):

<tbody>
    for (var i=0; i < numrows; i++) {
        <ObjectRow/>
    } 
</tbody>

我意识到并理解为什么这不是有效的 JSX,因为 JSX 映射到函数调用.但是,来自模板领域并且是 JSX 的新手,我不确定如何实现上述目标(多次添加组件).

I realize and understand why this isn't valid JSX, since JSX maps to function calls. However, coming from template land and being new to JSX, I am unsure how I would achieve the above (adding a component multiple times).

推荐答案

使用 Array map 函数是循环遍历 Array 元素并创建React 中的组件.这是在 JSX 中执行循环的一种很好的方法,它非常有效并且是一种整洁的循环方式.这不是唯一的方法,而是首选的方法.

Using the Array map function is a very common way to loop through an Array of elements and create components according to them in React. This is a great way to do a loop which is a pretty efficient and is a tidy way to do your loops in JSX. It's not the only way to do it, but the preferred way.

此外,不要忘记根据需要为每次迭代设置一个唯一键.ma​​p 函数从 0 创建唯一索引,但不建议使用生成的索引,但如果您的值是唯一的或者如果有唯一键,则可以使用它们:

Also, don't forget having a unique Key for each iteration as required. The map function creates a unique index from 0, but it's not recommended using the produced index, but if your value is unique or if there is a unique key, you can use them:

<tbody>
  {numrows.map(x=> <ObjectRow key={x.id} />)}
</tbody>

另外,如果您不熟悉 Array 上的 map 函数,请参考 MDN 中的几行:

Also, a few lines from MDN if you not familiar with the map function on Array:

map 为每个元素调用一次提供的回调函数数组,并根据结果构造一个新数组.打回来仅对已分配值的数组索引调用,包括未定义.不要求缺少的元素数组(即从未设置的索引,已被设置已删除或从未赋值).

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

callback 使用三个参数调用:元素的值,元素的索引,以及被遍历的 Array 对象.

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

如果向地图提供了 thisArg 参数,它将用作回调的这个值.否则,值 undefined 将用作它的这个值.这个回调最终可以观察到的值是根据通常的规则来确定这个看到的通过函数.

If a thisArg parameter is provided to the map, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value. This value ultimately observable by the callback is determined according to the usual rules for determining the this seen by a function.

map 不会改变调用它的数组(尽管回调,如果被调用,可能会这样做).

map does not mutate the array on which it is called (although callback, if invoked, may do so).

这篇关于在 React JSX 中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆