How to delete a ToDo Item onClick in React?

前端 未结 6 1278
感情败类
感情败类 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:18

    First, you would want the removeItem method to exist in the Todos class, since that is where that state is stored. Then, you can either use filter or slice

    export default class Todos extends Component {
        constructor(props) {
            super(props);
            this.state = { todos: [], text: '' };
        }
    
        addTodo(e) {
            e.preventDefault();
            this.setState({ todos: [ this.state.text, ...this.state.todos ] });
            this.setState({ text: ''});
        }
    
        updateValue(e) {
            this.setState({ text: [e.target.value]})
        }
    
        removeItem = index => {
            //either use filter
            const { todos } = this.state;
            const newTodos = todos.filter((todo, i) => i !== index);
            this.setState({ todos: newTodos});
    
            //or use slice
            const slicedNewTodos = todos.slice(0, index).concat(todos.slice(index + 1));
            this.setState({ todos: slicedNewTodos});
        }
    
        render() {
            return(
                
    this.addTodo(e)}> {this.updateValue(e)}} />
    ); } } import React, { Component } from 'react'; import { connect } from 'react-redux'; class TodoList extends Component { render() { return(
      { this.props.todos.map((todo, index) => { return
    • this.props.removeItem(index)} key={todo}>{ todo }
    • })}
    ); } }

提交回复
热议问题