简体   繁体   中英

Delete functionality is not working properly-Reactjs

i have created delete functionality,in which when user clicks delete[X] it has to get deleted from the respected row wrt datagrid view used in react

passing id as an parameter used _find index(loadlash)

problem:

1) selected Rows are not getting deleted.

code:

onclick event

      <div>
        <button onClick={() => this.deleteHandler(params.value)}>X</button>
      </div>

Delete code:

 deleteHandler = (id) => {
 const arrayPerson = this.props.rowData;
 const index = _.findIndex(this.props.rowData, { id: id });
 if (arrayPerson.indexOf(id) > -1) {
   arrayPerson.splice(index, 1);
   this.setState({ rows: arrayPerson });
 }

can any one help me on this issue.

This is a working example for this what if different is that you are passing the data from parent to child for that u can do multiple thing.

The Parent Component.

class TestComp extends React.Component {
constructor() {
    super();
    this.state = { listItems: [{ id: 1, text: "abc" }, { id: 2, text: "bcd" }, { id: 3, text: "dec" }] }
    this.handleRowClick = this.handleRowClick.bind(this);
}
handleRowClick(id) {

    const listItems = this.state.listItems;
    let copyListItems = [];
    listItems.forEach(function (item) {
        let objCopy = Object.assign({}, item);
        copyListItems.push(objCopy);
    });
    let updatedArray = _.remove(copyListItems, function (item) { return item.id == id; });

    this.setState({ listItems: copyListItems });
}
render() {

    return (
        <div>
            <ChildComp
                list={this.state.listItems}
                deleteHandler={this.handleRowClick}
            />
        </div>
    )
}
}

The Child Component that is receiving List items as props and when clicked the parent handler is being called which will update the List items and setState of Parent which will update the list being provided to child component hence it will be rendered.

export class ChildComp extends React.Component {

render() {
    let list = this.props.list.map((obj) =>
        <div key={obj.id} id={obj.id} style={{ padding: "10px", backgroundColor: "grey", border: "1px solid black" }} onClick={() => { this.props.deleteHandler(obj.id) }}> {obj.text} </div>
    );
    return (
        <div >
           {list}
        </div>
    )
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM