ReactJS how to delete item from list

后端 未结 1 418
情歌与酒
情歌与酒 2020-12-28 08:26

I have have code that creates

  • elements. I need to delete elements one by one by clicking. For each element I have Delete button. I under
  • 相关标签:
    1条回答
    • 2020-12-28 08:37

      You are managing the data in Parent component and rendering the UI in Child component, so to delete item from child component you need to pass a function along with data, call that function from child and pass any unique identifier of list item, inside parent component delete the item using that unique identifier.

      Step1: Pass a function from parent component along with data, like this:

      <TodoList items={this.state.items} _handleDelete={this.delete.bind(this)}/>
      

      Step2: Define delete function in parent component like this:

      delete(id){
          this.setState(prevState => ({
              data: prevState.data.filter(el => el != id )
          }));
      }
      

      Step3: Call that function from child component using this.props._handleDelete():

      class TodoList extends React.Component {
      
          _handleDelete(id){
              this.props._handleDelete(id);
          }
      
          render() {
              return (
                  <ul>
                      {this.props.items.map(item => (
                          <li key={item.id}>{item.text}<button onClick={this._handleDelete.bind(this, item.id)}>Delete</button></li>
                      ))}
                  </ul>
              );
          }
      }
      

      Check this working example:

      class App extends React.Component{
         constructor(){
            super();
            this.state = {
              data: [1,2,3,4,5]
            }
            this.delete = this.delete.bind(this);
         }
         
         delete(id){
            this.setState(prevState => ({
                data: prevState.data.filter(el => el != id )
            }));
         }
         
         render(){
            return(
                <Child delete={this.delete} data={this.state.data}/>
            );
         }
      }
      
      class Child extends React.Component{
      
         delete(id){
             this.props.delete(id);
         }
         
         render(){
            return(
               <div>
                 {
                    this.props.data.map(el=>
                        <p onClick={this.delete.bind(this, el)}>{el}</p>
                    )
                 }
               </div>
            )
         }
      }
      
      ReactDOM.render(<App/>, 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'/>

      0 讨论(0)
    提交回复
    热议问题