小编典典

从React js中的列表中删除项目

reactjs

我正在创建一个待办事项应用程序,当我们单击它们时,我无法编写用于删除列表元素的代码。我希望用户单击时删除特定项目

class Todo extends React.Component {

    constructor(props) {
      super(props);
      this.state={todos:[]};
    }

    save() {
      var todos = [...this.state.todos];
      todos.push(this.newText.value);
      this.setState({todos});
    }

    remove{

    }


    render(){
        return(
            <div className="list">
              <h1> TO-DO List</h1>
              <input type="text" ref={(ip) => {this.newText = ip}}/>
              <button onClick={this.save.bind(this)} className="btn btn-primary glyphicon glyphicon-floppy-saved">Save
              </button>
              <ul>
                {this.state.todos.map(function(todo) {
                      return <li>{todo}</li>

                 })}

              </ul>
            </div>
        )
    }
};

阅读 234

收藏
2020-07-22

共1个答案

小编典典

您需要传递待办事项的索引,然后使用javascript中的slice函数将其删除

remove(e, index){
      var todos = [...this.state.todos];
      todos.slice(index, 1);
      this.setState({todos})
}



class Todo extends React.Component {



    constructor(props) {

      super(props);

      this.state={todos:[]};

    }



    save() {

      var todos = [...this.state.todos];

      todos.push(this.newText.value);

      this.setState({todos});

    }



    deleteTodo(index){

        console.log(index)

         var todos = [...this.state.todos];

         todos.splice(index, 1)

         this.setState({todos})

    }





    render(){

        return(

            <div className="list">

              <h1> TO-DO List</h1>

              <input type="text" ref={(ip) => {this.newText = ip}}/>

              <button onClick={this.save.bind(this)} className="btn btn-primary glyphicon glyphicon-floppy-saved">Save

              </button>

              <ul>

                {this.state.todos.map(function(todo, index) {

                      return <li key={index} onClick={this.deleteTodo.bind(this, index)}>{todo}</li>



                 }.bind(this))}



              </ul>

            </div>

        )

    }

};



ReactDOM.render(<Todo/>, document.getElementById('app'))


<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>
2020-07-22