ReactJS how to delete item from list

后端 未结 1 423
情歌与酒
情歌与酒 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:

      
      

      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 (
                  
        {this.props.items.map(item => (
      • {item.text}
      • ))}
      ); } }

      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(
                
            );
         }
      }
      
      class Child extends React.Component{
      
         delete(id){
             this.props.delete(id);
         }
         
         render(){
            return(
               
      { this.props.data.map(el=>

      {el}

      ) }
      ) } } ReactDOM.render(, document.getElementById('app'))
      
      
      
      

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