javascript - 如何在 React 中获取单击动态添加的组件的索引并将其删除?
问题描述
我创建了一个自定义组件<Card />
。在主页上,我添加了一个按钮,一旦添加了卡片,就会添加这些卡片,每张卡片都有一个特定的删除按钮,该按钮应该从一堆卡片中删除该特定卡片。
这是我的代码:
添加功能添加卡片:
handleAddComponent() {
this.setState({
component: [
...this.state.component,
<Card remove={this.handleRemoveRow} />
]
});
}
移除卡片移除功能:
handleRemoveRow(event) {
// console.log(event.target.);
this.setState({
component: this.state.component.slice(0, -1)
});
}
和渲染:
render() {
return (
<section>
{this.state.component}
<button onClick={this.handleAddComponent}>
<span>Add</span>
</button>
</section>
);
}
这段代码的问题是,每当我单击删除按钮时,只有最后一个不符合我条件的组件被删除,我想删除一张特定的卡。component: this.state.component.slice(0, -1)
这将删除最后一个组件。
有没有其他方法可以获取每个卡片组件的索引,以便删除特定卡片?
解决方案
handleAddComponent() {
this.setState({
component: [
...this.state.component,
<Card remove={() => this.handleRemoveRow(this.state.component.length)} />
]
});
}
handleRemoveRow = i => {
this.setState({
component: this.state.component.filter((el, j) => j === i)
});
}
推荐阅读
- python - Pip install 未检测到的故障模式
- azure-devops - 自托管代理上的 Azure DevOps Python Pipeline Agent.ToolsDirectory 错误
- postgis - 如何在 PostGIS 数据库中存储值网格,以便 GeoServer 对其进行轮廓化?
- asp.net-mvc - 在 ASP.NET MVC 5 中将 SQL 查询转换为 lambda 表达式
- python - 自定义默认用户模型后 /admin/login/ 的 FieldError
- mysql - 如何在 Ubuntu 中离线安装 Mysql-server
- r - XGBoost xgbTree 的插入符号 varImp 包装器是否使用 XGBoost Gain?
- c - 将指向结构的指针传递给函数的C问题
- java - 在 java 中使用模式 regx 为给定的 4 种情况生成唯一模式
- numpy - Numpy 花式索引导致选择不同的形状