ReactJS可编辑表格单元格

时间:2017-07-14 02:32:36

标签: javascript reactjs

我想编辑和更新单个表格单元格值。我创建了一个函数(返回一堆选项)来调用该特定单元格的onClick但是在任何单元格的onClick上,该列中的所有元素都被替换。

我做错了什么?

https://jsfiddle.net/gkLe4qu0/ (我说的是状态栏)

<tbody>
  {requestsFiltered.map((request, i) =>(
    <tr key={i} className={request.status}>
      <td> {request.title} </td>
      <td onClick={() => this.editStatus(event)}>
        <a id={request.id} data-toggle="tooltip" title="Click to edit status">
          {
            this.state.isStatusClicked ? <StatusOptions /> : request.status
          }
        </a>
      </td>
      <td> {request.created_at.format('YYYY-MM-DD')} </td>
      <td> {request.updated_at.format('YYYY-MM-DD')} </td>
      <td>
        <a href="#" id={request.id} onClick={() => this.deleteRow(event)}> 
          Delete 
        </a> 
      </td>
    </tr>
  ))}
</tbody>

1 个答案:

答案 0 :(得分:1)

正如Hardik Modha在评论中所提到的,您缺少行级别标识,但您可以利用map索引来实现此功能。无需保持单独的statusId's左右。

<tbody>
  {requestsFiltered.map((request, i) =>(
    <tr key={i} className={request.status}>
      <td> {request.title} </td>
      <td onClick={() => this.editStatus(event, i)}>
        <a id={request.id} data-toggle="tooltip" title="Click to edit status">
          {
            this.state.isStatusClicked == i ? <StatusOptions /> : request.status
          }
        </a>
      </td>
      <td> {request.created_at.format('YYYY-MM-DD')} </td>
      <td> {request.updated_at.format('YYYY-MM-DD')} </td>
      <td>
        <a href="#" id={request.id} onClick={() => this.deleteRow(event)}> 
          Delete 
        </a> 
      </td>
    </tr>
  ))}
</tbody>

并将editStatus改为:

editStatus(event, index){
      console.log("edit status clicket");
      console.log(event.target.id);
      this.setState ({
          isStatusClicked: index
      })
}

参考所做的更改:https://jsfiddle.net/nagtan3/gkLe4qu0/4/

您仍然需要修改组合框更改的选择:

applyStatusChange(event, index) {
    const {value} = event.target;
    let newRequestData = this.state.requests.slice();

    newRequests[index]['status'] = value;
    this.setState ({
      requests: newRequests
    })
}

并使用上述方法:

<tbody>
      {requestsFiltered.map((request, i) =>(
        <tr key={i} className={request.status}>
          <td> {request.title} </td>
          <td onClick={() => this.editStatus(event, i)}>
            <a id={request.id} data-toggle="tooltip" title="Click to edit status">
              {
                this.state.isStatusClicked == i ? <StatusOptions onChangeMethod={(event) => applyStatusChange(event, i)} /> : request.status
              }
            </a>
          </td>
          <td> {request.created_at.format('YYYY-MM-DD')} </td>
          <td> {request.updated_at.format('YYYY-MM-DD')} </td>
          <td>
            <a href="#" id={request.id} onClick={() => this.deleteRow(event)}> 
              Delete 
            </a> 
          </td>
        </tr>
      ))}
    </tbody>