首页 > 解决方案 > 从 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" />

标签: reactjstypescript

解决方案


更新:

您好,我找出了问题所在,并在您的应用程序上成功删除了事件。

在这个代码框里,所有的东西都用注释来说明。

=========

我修改了这个,它应该使用 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});
}

推荐阅读