- <span style="font-family:Arial, Helvetica, sans-serif;background-color:rgb(255,255,255);">函数绑定: 函数进行 bind(绑定) 可以确保在函数中的 this 作为组件实例的引用,也就是说你想在自定义的函数中使用this,那么请先进行将此函数bind(this)。</span>
常用的函数绑定方式有如下几种:
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');
- }}