[React]自訂表格生成




<!DOCTYPE html>
<html>
<head>
  <title></title>

<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
</style>

</head>
<body>
 <div id="root">
  <!-- render here  -->
 </div> 

<script src="react/react.js"></script>
<script src="react/react-dom.js"></script> 
<!-- babel 5.8.24  -->
<script src="browser.js"></script>

 
<script type="text/babel" >
const numbers = [1, 2, 3, 4, 5];
const tableRow=null

class MyTable extends React.Component{
  constructor(props){
    super(props)
    this.state={
      tableRow:null,
      tableCol:null
    }

    this._setTable=this.setTable.bind(this)
  }

  setTable(){
    var trow=document.getElementById("row").value
    var tcol=document.getElementById("col").value
    console.log("row:"+trow)
    console.log("col:"+tcol)

    //ary init
    var colNum=[tcol]
    for(var i=0;i<tcol;i++){
      colNum[i]=i
    }

    //ary init 
    var rowNum=[trow]
    for(var i=0;i<trow;i++){
      rowNum[i]=i
    }

    const tableCol = colNum.map((idx)=>
      <th key={idx.toString()}>title:{idx}</th>
    );

    const cell = colNum.map((idx)=>
      <td key={idx.toString()}>new cell</td>
    );
    
    const tableRow = rowNum.map((idx) =>
       <tr key={idx.toString()}>
        {cell}
      </tr>
    );

    this.setState({
      tableRow:tableRow,
      tableCol:tableCol
    })
    
  }

  render(){
    return(
      <div>

      <table>
      <thead>
      <tr>
      {this.state.tableCol}
      </tr>
      </thead>
      <tbody>
      {this.state.tableRow}
      </tbody>
      </table>
    
      <form>
      <label>
      col:
      <input type="text" name="col" id="col" />
      row:
      <input type="text" name="row" id="row" />
      </label>
      <input type="button" value="set" onClick={this._setTable} />
      </form>

      </div>
    )
  }
}

ReactDOM.render(
  <MyTable />,
  document.getElementById('root')
);

</script>
</body>
</html>

原始檔案下載

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料