我对拖放元素使用了库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" />
更新:
嗨,我知道了出了什么问题,并在您的应用程序上成功执行了删除事件。
在此codeandbox上用注释说明了所有内容。
=========
我修改了这个,它应该使用Array的filter方法来完成所需的工作。
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}); }