使用React在表中合并2个或更多单元格

时间:2016-04-27 03:17:24

标签: javascript reactjs merge

我是React的新手。尝试创建合并单元格的功能。在普通的js中,我会传递td的引用来访问样式或其他属性。但是这里传递这个是绑定整个班级。我如何参考特定细胞。我也尝试将单元格和行号的索引传递给合并函数,但是click事件没有按预期工作。以下是我正在处理的代码段。对如何合并表中的2个单元格有所了解。感谢

function getTabularStateFromStore(){
  return(
    {
      row: 0,
      col: 0,
      rows:[]
    }
  )
}
class Table extends React.Component{
  constructor(){
    super();
    this.state = getTabularStateFromStore();
    this.onChangeOfRow = this.onChangeOfRow.bind(this);
    this.onChangeOfCol = this.onChangeOfCol.bind(this);
    this.merge = this.merge.bind(this);
  }
  render(){
     let rows = this.state.rows.map((row,index) => {
       var cells = [];
       for (var i in row) {
        cells.push(<td rowSpan={row[i].rowSpan} colSpan={row[i].colSpan} style={{minWidth: "30px", "padding":"5px"}} key={i} onClick={this.merge}></td>);
      }
      return <tr key={index}>{cells}</tr>;
    });
    return(
      <div>
        <div>
          <input type="number" size="4" value={this.state.row} default min="0" onChange={this.onChangeOfRow} />
          <input type="number" size="4" value={this.state.col} min="0" onChange={this.onChangeOfCol} />
        </div>
        <table>
          <tbody>
            {rows}
          </tbody>
        </table>
      </div>
    );
  }
  merge(cell, row) {
        //o.style.backgroundColor = "red";
        console.log("cell number: "+cell);
        console.log("row number: "+row);

    }
  onChangeOfRow(e) {
    this.updateRowsData(Number(e.target.value), this.state.col)
  }
  onChangeOfCol(e) {
    this.updateRowsData(this.state.row, Number(e.target.value))
  }
  updateRowsData(row, col){
    let rows = []
    for(var i = 0; i < row; i++){
       let cells = []
       for(var j = 0; j < col; j++){
         cells.push(Object.assign({value:"", rowSpan: 1, colSpan: 1}));
    }
     rows.push(cells);
   }
   this.setState({rows: rows, row: row, col: col})
  }
}
export default Table;

0 个答案:

没有答案