Delete an element by key from Array

前端 未结 2 1122
猫巷女王i
猫巷女王i 2021-01-26 13:30

I used library react-sortable-hoc for drag and drop element, but the library documentation does not have any actions for delete items. I want to delete, drag and drop item when

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-26 13:57

    So there were few problems in your code! You seemed to be confuse how react works with passing down props. You have to pass down the method required for remove. And you should bind it inside the class that you will be calling it.

    • onRemove should be bound to current context
    • onRemove should be passed down across the component tree
    • Check my //[NOTE]====> comments for additional explanation
    • Working code sandbox is 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) => (
        
    ) ); const SortableList = SortableContainer(({ items }: { items: string[] }) => { return (
    {items.map((value, index) => ( ))}
    ); }); 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 ; } 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(, document.getElementById("root"));

提交回复
热议问题