问题
How to change a particular row that is clicked in JSX table to change to input editable row without using any libraries such as react-table?
<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>})}
the above is the code to display table. this.state.students has the student details from db. I want the particular table row to be changed to a row of input fields on click. Kindly help. I'm new to the world of react.
回答1:
If I understand your question correctly, it seems like you need to track additional state to determine if a "student" row is currently in editing mode or not. Perhaps you could achieve that by doing something like this:
<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 - hope that helps!
来源:https://stackoverflow.com/questions/52844544/add-edit-fields-on-table-row-on-click-in-reactjs-without-using-react-table-libra