天天看點

react函數綁定this的方式。

第一種:如果函數寫在了render上面。就把this綁定到構造函數裡面,

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      soldiers : ['dad','father','mother']
    }
    /*綁定this到函數裡面方式一*/
    this.function_name = this.function_name.bind(this);

  }
  /*函數可以寫在這裡。render上面*/
  addsoldier (){
    this.setState({
     soldiers: [...this.state.soldiers,'新兵'+Math.random()]
    })
  }
  render(){}
           

第二種:直接綁定到要執行的onClick = {this.function_name.bind(this)}

裡面。

第三種:在要執行的函數的地方寫成箭頭函數。

onClick = {()=>this.function_name()}
           

第四種:把函數直接寫成箭頭函數:

function_name = () =>{
console.log()

onClick = {this.function_name}
}
           

記錄一種函數參數的傳遞:

addsoldier =(e)=>{
    console.log(e);
    this.setState({
     soldiers: [...this.state.soldiers,'新兵'+Math.random()]
    })
  }

<button onClick={this.addsoldier.bind(this,'111')}>添加新兵</button>