2016-02-07 76 views
9

我有一個多維數組:數組results包含18個數組row,每個包含6個數字。如何迭代React組件中的嵌套數組?

我想將其作爲表格呈現。邏輯將是

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

但我無法弄清楚如何在JSX中寫這個。

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

但這是不對的。這是什麼程序,你如何嵌套地圖調用和插值?

回答

6

一種方式做到這一點

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') 
); 

在行動:https://jsfiddle.net/69z2wepo/30476/

4

我建議組分中分離到ResultsetNumberComponent並嘗試與箭頭功能是一致的。

// 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

這個工作很適合我來映射數組的數組,我有一個名爲包含數組根數組,我成立了以功能爲這樣:

//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) 
    ) 
}