函數綁定: 函數進行 bind(綁定) 可以確保在函數中的 this 作為組件實例的引用,也就是說你想在自定義的函數中使用this,那么請先進行將此函數bind(this)。常用的函數綁定方式有如下幾種:
1. 在生命周期函數中綁定,如下:
constructor(PRops) { super(props); this.state = {}; this.test = this.test.bind(this) }2. 使用的地方直接綁定,如下:
onPress={this.test.bind(this)}3. 直接在使用的地方直接寫:
onPress={()=>{ Alert.alert('Hello World');}}
新聞熱點
疑難解答