本文翻译自:Loop inside React JSX
I'm trying to do something like the following in React JSX
(where ObjectRow is a separate component): 我正在React JSX
尝试执行以下操作(其中ObjectRow是一个单独的组件):
<tbody>
for (var i=0; i < numrows; i++) {
<ObjectRow/>
}
</tbody>
I realize and understand why this isn't valid JSX
, since JSX
maps to function calls. 我意识到并理解为什么这不是有效的JSX
,因为JSX
映射到函数调用。 However, coming from template land and being new to JSX
, I am unsure how I would achieve the above (adding a component multiple times). 但是,由于来自模板领域并且是JSX
新手,所以我不确定如何实现上述目标(多次添加组件)。
#1楼
参考:https://stackoom.com/question/1XzLW/在React-JSX内部循环
#2楼
Think of it like you're just calling JavaScript functions. 就像您只是在调用JavaScript函数一样。 You can't use a for
loop where the arguments to a function call would go: 您不能在for
循环中使用函数调用的参数:
return tbody(
for (var i = 0; i < numrows; i++) {
ObjectRow()
}
)
See how the function tbody
is being passed a for
loop as an argument, and of course that's a syntax error. 了解如何将函数tbody
作为参数传递给for
循环,这当然是语法错误。
But you can make an array, and then pass that in as an argument: 但是您可以创建一个数组,然后将其作为参数传递:
var rows = [];
for (var i = 0; i < numrows; i++) {
rows.push(ObjectRow());
}
return tbody(rows);
You can use basically the same structure when working with JSX: 使用JSX时,可以使用基本相同的结构:
var rows = [];
for (var i = 0; i < numrows; i++) {
// note: we add