ReactNative綁定函數中的this

在一個button的onpress方法中傳進一個函數back,這個函數中如果用到this的話,需要將back中的this進行綁定操作。

1、傳入時進行綁定

onPress={this.back.bind(this)}

2、在constructor中綁定

constructor(props){
  super(props)
  this.state = {
    show : true,
  }
  this.back = this.back.bind(this);
}

3、在函數定義時進行綁定

onPress={this.back}
....
  back = () => {
        const {navigator} = this.props;
        navigator.pop();
    }

()=>{} 這種形式的代碼,語法規定就是(function(){}).bind(this),即自動添加了bind this。 參考鏈接

RN的聲明週期

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章