Creating simple table

Sorry for what it appears to be a newbie question (been up working late and just got started with React) but I am trying to figure out how to just render a simple table with n x n dimension.

For instance, in my component, the render output would be something like this:

      <table id="simple-board">
        <tbody>
          <tr id="row0">
            <td id="cell0-0"></td>
            <td id="cell0-1"></td>
            <td id="cell0-2"></td>
          </tr>
          <tr id="row1">
            <td id="cell1-0"></td>
            <td id="cell1-1"></td>
            <td id="cell1-2"></td>
          </tr>
          <tr id="row2">
            <td id="cell2-0"></td>
            <td id="cell2-1"></td>
            <td id="cell2-2"></td>
          </tr>
        </tbody>
      </table>

where each row has it's own id , as well as each cell.

The initial state

  constructor(props){
    super(props);
    this.state = {size: 3}
  }

is what set the size of the table.

What threw me of was how to implement a for loop inside the JSX.


After a good night sleep, I was able to figure it out:

import React, { Component } from 'react'

export default class Example extends Component {
  constructor(props){
    super(props);
    this.state = {size: 3}
  }
  render(){
    let rows = [];
    for (var i = 0; i < this.state.size; i++){
      let rowID = `row${i}`
      let cell = []
      for (var idx = 0; idx < this.state.size; idx++){
        let cellID = `cell${i}-${idx}`
        cell.push(<td key={cellID} id={cellID}></td>)
      }
      rows.push(<tr key={i} id={rowID}>{cell}</tr>)
    }
    return(
      <div className="container">
        <div className="row">
          <div className="col s12 board">
            <table id="simple-board">
               <tbody>
                 {rows}
               </tbody>
             </table>
          </div>
        </div>
      </div>
    )
  }
}

Thanks all for responding!


像这样的东西:

  <table id="simple-board">
    <tbody>
     {this.props.yourData.slice(0,this.state.size).map((item , index)=>{

        return(
      <tr key={index} id={`row${index}`}>
         {item.felanBisar.map((item2,index2)=>{
          return(
             <td id={`cell${index}-{index2}`}></td>
           );
          })}
      </tr>
       );
      })}
    </tbody>
  </table>
链接地址: http://www.djcxy.com/p/52056.html

上一篇: JSX for ... in循环

下一篇: 创建简单的表格