如何在不使用任何库(例如react-table)的情况下更改在JSX表中单击的特定行以更改为输入可编辑行?
<table className="table-data">
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
<th>Class</th>
<th>Section</th>
</tr> {this.state.students.map((item,key) => {return
<Fragment key={key}>
<tr key={key} onClick={()=>
{this.setState({clientIsEditing:true},this.edit(key,item))}}>
<td>{item[1]}</td>
<td>{item[2]}</td>
<td>{item[3]}</td>
<td>{item[4]}</td>
</tr>
</Fragment>
<tbody>
</table>})}
上面是显示表格的代码。 this.state.students
拥有来自db的学生详细信息。我希望在单击时将特定的表行更改为一行输入字段。请帮助。我是反应世界的新手。
答案 0 :(得分:0)
如果我正确理解了您的问题,似乎您需要跟踪其他状态才能确定“学生”行当前是否处于编辑模式。也许您可以通过执行以下操作来实现:
<table className="table-data">
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
<th>Class</th>
<th>Section</th>
</tr>
{ this.state.students.map((item,key) => {
const editField = (value, index) => {
// Clone students data before mutation
const students = this.state.students.map(item => ({ ...item }))
// Update field by index of current student
students[key][index] = value
// Trigger re-render
this.setState({ students })
}
return (
<tr key={key} className={ item.editing ? 'editing' : '' } onClick={()=> {
// Clone students data before mutation
const students = this.state.students.map(i => ({ ...i, editing : item.editing && i===item }))
// Toggle editing flag of this current student (ie table row)
students[key].editing = true;
// Trigger re-render
this.setState({
clientIsEditing:true, // This might not be needed ?
students
})
}
}>
<td>{ item.editing ? <input value={item[1]} onChange={ e => editField(e.target.value, 1) } /> : <span>{item[1]}</span> }</td>
<td>{ item.editing ? <input value={item[2]} onChange={ e => editField(e.target.value, 2) } /> : <span>{item[2]}</span> }</td>
<td>{ item.editing ? <input value={item[3]} onChange={ e => editField(e.target.value, 3) } /> : <span>{item[3]}</span> }</td>
<td>{ item.editing ? <input value={item[4]} onChange={ e => editField(e.target.value, 4) } /> : <span>{item[4]}</span> }</td>
</tr> )
})
}
</tbody>
</table>
Here is a working jsFiddle as well-希望能有所帮助!