Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - 在React JSX内部循环(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新手,所以我不确定如何实现上述目标(多次添加组件)。)

  ask by Ben Roberts translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 a key prop here to allow react to uniquely identify each
    // element in this array. see: https://reactjs.org/docs/lists-and-keys.html
    rows.push(<ObjectRow key={i} />);
}
return <tbody>{rows}</tbody>;

Incidentally, my JavaScript example is almost exactly what that example of JSX transforms into.

(顺便说一句,我的JavaScript示例几乎就是该JSX示例转换成的示例。)

Play around with Babel REPL to get a feel for how JSX works.

(与Babel REPL一起玩,以了解JSX的工作方式。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...