2016-02-07 6 views
9

Ho un array multidimensionale: un array results contenente 18 array row, ciascuno contenente 6 numeri.Come faccio a ripetere gli array annidati in un componente React?

Voglio renderlo come una tabella. La logica sarebbe

results.each as (row) 
    <tr> 
     row.each as (number) 
       <td>number</td> 
    </tr> 

Ma non riesco a capire come lo scrivere in JSX.

const Resultset = props => (
    {props.rows.map(rows => { 
     <tr> 
      {rows.map(number => <td>{number}</td>)} 
     </tr> 
    })} 
); 

Ma non è giusto. Qual è la procedura per questo, come annidi le chiamate e le interpolazioni della mappa?

risposta

6

Un modo per farlo

var arr = [ [ 2, 3, 4, 5, 6, 7 ], 
    [ 8, 9, 10, 11, 12, 13 ], 
    [ 14, 15, 16, 17, 18, 19 ], 
    [ 20, 21, 22, 23, 24, 25 ], 
    [ 26, 27, 28, 29, 30, 31 ], 
    [ 32, 33, 34, 35, 36, 37 ], 
    [ 38, 39, 40, 41, 42, 43 ], 
    [ 44, 45, 46, 47, 48, 49 ], 
    [ 50, 51, 52, 53, 54, 55 ], 
    [ 56, 57, 58, 59, 60, 61 ], 
    [ 62, 63, 64, 65, 66, 67 ], 
    [ 68, 69, 70, 71, 72, 73 ], 
    [ 74, 75, 76, 77, 78, 79 ], 
    [ 80, 81, 82, 83, 84, 85 ], 
    [ 86, 87, 88, 89, 90, 91 ], 
    [ 92, 93, 94, 95, 96, 97 ], 
    [ 98, 99, 100, 101, 102, 103 ], 
    [ 104, 105, 106, 107, 108, 109 ] ]; 

var Hello = React.createClass({ 
    tablerows: function() { 
    return this.props.arr.map(rows => { 
     var row = rows.map(cell => <td>{cell}</td>); 
     return <tr>{row}</tr>; 
    }); 
    }, 
    render: function() { 
    return <table>{this.tablerows()}</table>; 
    } 
}); 

ReactDOM.render(
    <Hello arr={arr} />, 
    document.getElementById('container') 
); 

In azione: https://jsfiddle.net/69z2wepo/30476/

4

Vorrei suggerire che separa i componenti da Resultset, NumberComponent e cercare di essere coerente con le funzioni di direzione.

// Explicit return 

const NumberComponent = props => { 
    return (
     <td>{ props.number }</td> 
    ) 
} 

const Resultset = props => { 
    return (
     <tr> 
      { 
       props.rows.map(number => <NumberComponent number={number} />) 
      } 
     </tr> 
    ) 
} 

// Implicit return 

const NumberComponent = props => (<td>{ props.number }</td>); 

const Resultset = props => (
    <tr> 
     { 
      props.rows.map(number => <NumberComponent number={number} />) 
     } 
    </tr> 
); 
0

questo ha funzionato bene per me per mappare un array di array, ho chiamato l'array che contiene array radice, ho creato a funzioni così:

//root render function 

renderNested = (row, i) => { 
    return (
     root.map(function (row, i) { 
      return (
      <div key={i}> 
       {this.renderNested(row, i)} 
      </div> 
      ) 
     }, this) 
    ) 
} 

//nested render function 

renderNested = (row, i) => { 
    return (
     row.map(function (innerrow, ii) { 
      return(
       <span key={ii}> 
        Nested content here 
       </span> 
      ) 
     }, this) 
    ) 
}