React JSX inner loop
P粉966979765
2023-08-23 14:08:12
<p>I'm trying to do something like the following in React JSX (where the ObjectRow is a separate component): </p>
<pre class="brush:php;toolbar:false;"><tbody>
for (var i=0; i < numrows; i ) {
<ObjectRow/>
}
</tbody></pre>
<p>I realize and understand why this is not valid JSX, since JSX maps to function calls. However, coming from the template world and new to JSX, I'm not sure how to achieve the above goal (adding components multiple times). </p>
I'm not sure if this is appropriate for your case, but usually map is a good answer.
If this is your code using a for loop:
You can use map to write 一> like this:
ES6 syntax:
Think of it as if you were just calling a JavaScript function. You cannot use a
for
loop to pass arguments to a function call:See how the function
tbody
is passed as a parameter to thefor
loop - causing a syntax error.But you can create an array and pass it as a parameter:
You basically use the same structure when using JSX:
By the way, my JavaScript example converts almost exactly the same thing as the JSX example. Try using Babel REPL to get a feel for how JSX works.