Removing elements react

Delete elements, do not directly manipulate the value inside the state, you need to copy the value to be changed. So use the expand operator, copy over the array.

import React ,{Component} from 'react'
class App extends Component{
  constructor(props){
    super(props)
    this.state = {
      list: [ "Monday", "Tuesday", "Wednesday"],
      inputValue:""
    }
  }
  render(){
    return(
      <div>
        {
          this.state.list.map((ele,index)=>{
            // The index passed
            return <p key={index} >{ele}<button onClick={this.del.bind(this,index)}>删除</button></p>  
          })
        }
        <input type="text" value={this.state.inputValue} onChange={this.change.bind(this)}/>
        <button onClick={this.add.bind(this)}>添加</button>
      </div>
    )
  }

  change (e) {
    this.setState({
      inputValue:e.target.value
    })
  }

  add(){
    this.setState({
      list:[...this.state.list,this.state.inputValue],
      inputValue:""
    })
  }

  del(index){
    // expand Arrays
    var list = [...this.state.list]
    // delete elements
    list.splice(index,1)
    this.setState({
      list:list
    })
  }
}
export default App;

  

Guess you like

Origin www.cnblogs.com/luguankun/p/11029039.html