reactjs - 从 Array 中按键删除一个元素
问题描述
我将库react-sortable-hoc用于拖放元素,但库文档没有任何删除项目的操作。单击关闭按钮时,我想删除,拖放项目。哪种方法适合从对象中按键删除元素?
反应
const SortableItem = SortableElement(({ value }: { value: string }, onRemove: any) =>
<div className="dragItems" style={{ background: 'gray' }}>
<img src={value} alt="" />
<button className="dragCloseBtn" onClick={() => onRemove(any)} />
</div>
);
const SortableList = SortableContainer(({ items }: { items: string[] }) => {
return (
<div className="dragAndDrop">
{items.map((value, index) => (
<SortableItem key={'item-${index}'} index={index} value={value} />
))}
</div>
);
});
constructor(props: any) {
super(props);
this.state = {
items: [
{
"id": 0,
"link": "https://via.placeholder.com/150"
},
{
"id": 1,
"link": "https://via.placeholder.com/150"
}
],
};
}
public onSortEnd = ({ oldIndex, newIndex }: { oldIndex: number, newIndex: number }) => {
this.setState({
items: arrayMove(this.state.items, oldIndex, newIndex),
});
};
public onRemove(e: { target: { value: any; }; }) {
const array = [...this.state.items];
const index = array.indexOf(e.target.value)
if (index !== -1) {
array.splice(index, 1);
this.setState({items: array});
}
}
<SortableList items={this.state.items}
onSortEnd={this.onSortEnd}
lockAxis="xy"
axis="xy" />
解决方案
更新:
您好,我找出了问题所在,并在您的应用程序上成功删除了事件。
在这个代码框里,所有的东西都用注释来说明。
=========
我修改了这个,它应该使用 Array 的filter
方法完成所需的操作。
public onRemove(e: { target: { value: any; }; }) {
let array = [...this.state.items];
const intId = parseInt(e.target.value, 10);
array = array.filter(item => item.id !== intId);
this.setState({items: array});
}
推荐阅读
- asp.net-core - 如何使用 URL 重写中间件 asp core 2.2?
- php - 作曲家安装中的 symfony 属性访问错误
- angular - Angular 7 Bootstrap 4 侧边栏
- search - 如何在多个 DOCX 文件中搜索 Word 字段中的字符串?
- javascript - 如果阈值为 Number.MIN_VALUE,则在数组中查找超过某个阈值的最小值的函数不会找到低于 1 的数字。如何解决这个问题?
- python - Python 数据相关错误:列表索引必须是整数或切片,而不是 str
- c - 在不同上下文中使用“绑定”系统调用的“地址已在使用”(EADDRINUSE)问题
- node.js - 谷歌云功能节点JS SFTP到云存储传输文件错误
- powershell - Powershell 压缩存档
- xcode - 如何将 Xcode 上的编译器更改为 gcc 7.3.0?