通过数组中的键删除元素

时间:2019-07-09 09:58:07

标签: reactjs typescript

我将库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" />

2 个答案:

答案 0 :(得分:1)

已更新

您好,我弄清楚出了什么问题,并在您的应用程序上成功执行了删除事件。

在此codesandbox上用注释说明了一切。

=========

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

答案 1 :(得分:1)

因此,您的代码中几乎没有问题!您似乎很困惑反应如何传递道具。您必须传递删除所需的方法。并且应该将其绑定到将要调用的类中。

  
      
  • onRemove应该绑定到当前上下文
  •   
  • onRemove应该在组件树中向下传递
  •   
  • 检查我的/// [注] ====>评论以获取其他说明
  •   
  • 工作代码沙箱为here
  •   
import * as React from "react";
import * as ReactDOM from "react-dom";
import {
  arrayMove,
  SortableContainer,
  SortableElement
} from "react-sortable-hoc";


//[NOTE]====>value contains the relevent object containing the callback. Onclick call it with the relevant id
const SortableItem = SortableElement(
  ({ value }: { value: any }, onRemove: any) => (
    <div className="dragItems" style={{ background: "gray", margin: "20px" }}>
      <img src={value.link} alt="" />
      <button className="dragCloseBtn" onClick={() => value.onRemove(value.id)}>
        {" "}
        X{" "}
      </button>
    </div>
  )
);

const SortableList = SortableContainer(({ items }: { items: string[] }) => {
  return (
    <div className="dragAndDrop">
      {items.map((value, index) => (
        <SortableItem key={`item-${index}`} index={index} value={value} />
      ))}
    </div>
  );
});

class SortableComponent extends React.Component<{}, { items: string[] }> {
  constructor(props: {}) {
    super(props);

    //[NOTE]====>Send the callback on each element bound to the current context
    //This is like telling the function from where exactly the function will be called
    this.state = {
      items: [
        {
          id: 0,
          link: "https://via.placeholder.com/150",
          onRemove: this.onRemove.bind(this)
        },
        {
          id: 1,
          link: "https://via.placeholder.com/150",
          onRemove: this.onRemove.bind(this)
        }
      ]
    };
  }
  public render() {
    return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />;
  }
  public onSortEnd = ({
    oldIndex,
    newIndex
  }: {
    oldIndex: number;
    newIndex: number;
  }) => {
    this.setState({
      items: arrayMove(this.state.items, oldIndex, newIndex)
    });
  };

  //[NOTE]====>Use the id to filter out and set the new set of items
  public onRemove(id) {
    console.log(id);
    let array = [...this.state.items];
    const intId = parseInt(id, 10);
    array = array.filter((item: any) => item.id !== intId);
    this.setState({ items: array });
  }
}

ReactDOM.render(<SortableComponent />, document.getElementById("root"));