[英]How to add mapped element to state onClick?
In the render
of my App.js component I have table that displays items mapped from an array.在我的 App.js 组件的render
,我有一个表格显示从数组映射的项目。 The array has objects with string values for code
and mod_name
该数组具有带有code
和mod_name
字符串值的对象
...
{modules.map((mod, i) => (
<tr>
<td> {mod.code} </td>
<td> {mod.mod_name} </td>
<td>
<Input type="button" onClick={this.onCheckbox(mod.code)} />
</td>
</tr>
))}
...
The Input
is a checkbox, and I want to add/remove the mod.code
for the row based on if the checkbox is marked. Input
是一个复选框,我想根据复选框是否被标记来添加/删除该行的mod.code
。
Currently, my onCheckbox
method looks like this:目前,我的onCheckbox
方法如下所示:
onCheckbox (data) {
const arr = this.state.selected;
if(arr.includes(data)) {
const index = arr.indexOff(data)
if(index > -1) {
arr.splice(index, 1);
this.setState({selected: arr})
}
} else {
this.setState({selected: [...this.state.selected: arr]})
}
}
However, I get an error: Unhandled Rejection (Error): Maximum update depth exceeded.
但是,我收到一个错误: Unhandled Rejection (Error): Maximum update depth exceeded.
How should I go about doing this?我该怎么做呢?
{modules.map((mod, i) => (
<tr>
<td> {mod.code} </td>
<td> {mod.mod_name} </td>
<td>
<Input type="button" onClick={this.onCheckbox(mod.code)} />
<button onClick={()=> deleteHandle(mod)}>Delete</button>
</td>
</tr>
))}
function deleteHandle
函数deleteHandle
function deleteHandle=item=>{
let filtered = this.state.modules.filter(module=>module.id!==item.id);
this.setState({modules: filtered})
}
Like i created for button you can change as per your objective/requirement.就像我为按钮创建的一样,您可以根据您的目标/要求进行更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.