P粉6098665332023-08-24 11:18:53
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:
<tbody> for (var i=0; i < objects.length; i++) { <ObjectRow obj={objects[i]} key={i}> } </tbody>
You can use map to write 一> like this:
<tbody> {objects.map(function(object, i){ return <ObjectRow obj={object} key={i} />; })} </tbody>
ES6 syntax:
<tbody> {objects.map((object, i) => <ObjectRow obj={object} key={i} />)} </tbody>
P粉9377693562023-08-24 11:13:18
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:
return tbody( for (let i = 0; i < numrows; i++) { ObjectRow() } )
See how the function tbody
is passed as a parameter to the for
loop - causing a syntax error.
But you can create an array and pass it as a parameter:
const rows = []; for (let i = 0; i < numrows; i++) { rows.push(ObjectRow()); } return tbody(rows);
You basically use the same structure when using JSX:
const rows = []; for (let i = 0; i < numrows; i++) { // note: we are adding 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>;
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.