我在功能组件内部有一个表格。表格中的每一行在行末都有一个编辑按钮。当我单击“编辑”按钮时,它将更改应用于所有编辑按钮。我如何知道单击了哪个按钮并将更改仅应用于该按钮? (我有很多行,所以我不能为每个按钮创建状态)
答案 0 :(得分:3)
您可以执行的一种方法是跟踪状态中的行索引。例如,为按钮提供id
,它等于行的索引
<Button id={index} type="button" onClick={e => this.handleEdit(e)}>
以及您的handleEdit
函数中
handleEdit = e => {
e.preventDefault();
this.setState({
showbutton: true,
showButtonIndex: Number(e.target.id)
});
};
通过这种方式,您可以为状态中的已单击行创建索引,并且可以更改逻辑以将<Edit />
组件显示为
{this.state.showbutton && (this.state.showButtonIndex === index) && <Edit />}
我假设您一次只允许编辑一行。
工作代码here
答案 1 :(得分:1)
我不知道按钮的期望行为是什么,但是,这似乎是创建按钮的相关代码
handleEdit = (e) => {
e.preventDefault();
this.setState({
showbutton: true
});
};
render() {
console.log(this.state.names);
return (
<div>
<h2> Names: </h2>
<Table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
{this.state.names.map((name, index) => {
return (
<tbody>
<tr>
<td> {name} </td>
<td>
<Button type="button" onClick={e => this.handleEdit(e)}>
Edit
</Button>
</td>
{this.state.showbutton && <Edit />}
</tr>
</tbody>
);
})}
</Table>
</div>
);
}
您可以在this.states.map()函数中看到有绑定的索引参数。您可以使用它来跟踪哪个按钮正在调用该函数并将其传递给该函数
handleEdit = (e, id) => {
e.preventDefault();
console.log(id);
this.setState({
showbutton: true
});
};
render() {
console.log(this.state.names);
return (
<div>
<h2> Names: </h2>
<Table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
{this.state.names.map((name, index) => {
return (
<tbody>
<tr>
<td> {name} </td>
<td>
<Button type="button" onClick={e => this.handleEdit(e, index)}>
Edit
</Button>
</td>
{this.state.showbutton && <Edit />}
</tr>
</tbody>
);
})}
</Table>
</div>
);
}
该示例仅显示单击它的按钮的ID。您可以通过任何必要的方式利用它来唯一标识按钮。
代码为here
答案 2 :(得分:1)
我做了一些here