事件未绑定this
首先是js本身特性决定的
this永远指向最后调用它的那个对象
import React, { Component } from 'react';
import { View,Text } from 'react-native'
class Index extends Component {
constructor(props) {
super(props);
this.state = { }
}
handlePress(){
console.log(this.state);
}
render() {
return (
<View>
<Text onPress={this.handlePress}>未绑定this</Text>
</View>
);
}
}
export default Index;
事件绑定this
绑定事件需要注意this的指向问题,总结如下
1. 使用箭头函数
2. 通过bind绑定
3. 匿名函数
4. 在构造函数中绑定
使用箭头函数
import React, { Component } from 'react';
import { View,Text } from 'react-native'
class Index extends Component {
state = {
name:'Luka'
}
handlePress=()=>{
console.log(this.state);
}
render() {
return (
<View>
<Text onPress={this.handlePress}>箭头函数绑定</Text>
</View>
);
}
}
export default Index;
通过bind绑定
import React, { Component } from 'react';
import { View,Text } from 'react-native'
class Index extends Component {
state = {
name:'Luka'
}
handlePress(){
console.log(this.state);
}
render() {
return (
<View>
<Text onPress={this.handlePress.bind(this)}>通过bind绑定</Text>
</View>
);
}
}
export default Index;
通过匿名函数绑定
import React, { Component } from 'react';
import { View,Text } from 'react-native'
class Index extends Component {
state = {
name:'Luka'
}
handlePress(){
console.log(this.state);
}
render() {
return (
<View>
<Text onPress={()=>this.handlePress}>匿名函数</Text>
</View>
);
}
}
export default Index;
在构造函数中bind绑定
import React, { Component } from 'react';
import { View,Text } from 'react-native'
class Index extends Component {
constructor(props) {
super(props);
this.state = {
name:'Luka'
}
this.handlePress=this.handlePress.bind(this)
}
handlePress(){
console.log(this.state);
}
render() {
return (
<View>
<Text onPress={this.handlePress}>构造函数</Text>
</View>
);
}
}
export default Index;