How to delete a ToDo Item onClick in React?

前端 未结 6 1277
感情败类
感情败类 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条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-30 07:15

    You have called setState two times in the addTodo function. You can set todos and text in a single setState function like this:

    addTodo(e) {
        e.preventDefault();
        this.setState({ todos: [ this.state.text, ...this.state.todos ], text: '' });
    }
    

    Do not write removeItem function in TodoList Component as it is purely working on props. Pass a removeItem function from Todos to it and remove that item in Todos's removeItem function like this:

    import React, {Component} from 'react'
    export default class Todos extends Component {
      constructor(props) {
        super(props);
        this.state = { todos: [], text: '' };
        this.removeItem = this.removeItem.bind(this)
      }
    
      addTodo(e) {
        e.preventDefault();
        this.setState({ todos: [ this.state.text, ...this.state.todos ], text: '' });
      }
    
    
      updateValue(e) {
        this.setState({ text: [e.target.value]})
      }
      removeItem(index) {
        const todos = this.state.todos.filter((todo, todoIndex) => {
          return todoIndex !== index
        })
        this.setState({ todos })
      }
      render() {
        return(
          
    this.addTodo(e)}> {this.updateValue(e)}} />
    ); } } class TodoList extends Component { render() { return(
      { this.props.todos.map((todo, index) => { return
    • { this.props.removeItem(index)}} key={todo}>{ todo }
    • })}
    ); } }

    Hope, it helps.

提交回复
热议问题