How to delete a ToDo Item onClick in React?

前端 未结 6 1264
感情败类
感情败类 2020-12-30 06:32

I\'m doing a simple todo app with React, just to practise. How can I delete a list item, when clicking on it?

Here is my todos.js

export default cla         


        
6条回答
  •  萌比男神i
    2020-12-30 07:14

    Only thing to do is to move todos to state in TodoList and pass the index of the current todo in to the removeItem method. Then splice it as you suggested.

    In TodoList:

    constructor(props) {
        super(props);
    
        this.state = { todos: props.todos };
    }
    
    removeItem(index) {
        this.setState({
            todos: this.state.todos.filter((_, i) => i !== index)
        });
    }
    
    render() {
        return(
            
      { this.state.todos.map((todo, index) => { return
    • { this.removeItem(index)}} key={todo}>{ todo }
    • })}
    ); }

    Remove item courtesy of Removing element from array in component state

提交回复
热议问题