Loop in React JSX

Sto cercando di fare qualcosa come il seguente in React JSX (dove ObjectRow è un componente separato):

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

Mi rendo conto e capisco perché questo non è valido JSX, dal momento che JSX mappa le chiamate di funzione. Tuttavia, venendo dalla terra dei template ed essendo nuovo a JSX, non sono sicuro di come potrei ottenere quanto sopra (aggiungendo un componente più volte).

Soluzione

Pensatelo come se steste chiamando delle funzioni JavaScript. Non puoi usare un ciclo for dove andrebbero gli argomenti di una chiamata di funzione:

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

Vedete come alla funzione tbody viene passato un ciclo for come argomento, e naturalmente questo è un errore di sintassi.

Ma potete creare un array e poi passarlo come argomento:

var rows = [];
for (var i = 0; i < numrows; i++) {
    rows.push(ObjectRow());
}
return tbody(rows);

Puoi usare fondamentalmente la stessa struttura quando lavori con 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();
}
return <tbody>{rows}</tbody>;

Per inciso, il mio esempio JavaScript è quasi esattamente quello in cui si trasforma quell'esempio di JSX. Giocate con Babel REPL per avere un'idea di come funziona JSX.

Commentari (18)

Non so se questo funzionerà per la tua situazione, ma spesso map è una buona risposta.

Se questo fosse il tuo codice con il ciclo for:

<tbody>
    for (var i=0; i < objects.length; i++) {

    } 
</tbody>

Potresti scriverlo così con map:

<tbody>
    {objects.map(function(object, i){
        return ;
    })}
</tbody>

Sintassi ES6:

<tbody>
    {objects.map((object, i) => )}
</tbody>
Commentari (11)

So che questo è un vecchio thread, ma potresti voler controllare React Templates, che ti permette di usare template in stile jsx in react, con alcune direttive (come rt-repeat).

Il tuo esempio, se hai usato react-templates, sarebbe:

<tbody>

</tbody>
Commentari (1)