前言
原文地址:https://blog.csdn.net/weixin_34191845/article/details/86363163
控制台是在微信开发工具中使用
一开始的代码是这样的
handleClick(e) {
console.log("this", this);
console.log("setState", this.setState);
}
render() {
return (
<View className='index'>
<Text>Hello world!</Text>
<Button onClick={this.handleClick}>点击,content : </Button>
</View>
)
}
点击按钮后 打印的this与this.setState
我第一眼看见的时候觉得像H5的dom对象
最终解决
创建对象构造器,并给方法绑定构造器的this。
代码:
constructor(props) { //构造器
super(props);
this.state = { //设置该页面的数据,与本文无关
value: 1,
};
this.handleClick = this.handleClick.bind(this); // 给方法绑定this,并赋值。
}
handleClick(e) {
console.log("this", this);
console.log("setState", this.setState);
}
render() {
return (
<View className='index'>
<Text>Hello world!</Text>
<Button onClick={this.handleClick}>点击,content : </Button>
</View>
)
}
最终打印
后续 setState
1.setState 是异步执行的,所以在特别场景中可以使用 setState 方法的 回调函数
如下
this.state({
value:1
},() => {
//回调函数体
})
2.setState 是合并执行的
constructor(props) {
super(props);
this.state = {
value: 1,
num: 1,
}
this.change = this.change.bind(this);
}
change() {
this.setState({
value: 2,
}, () => {
console.log("value1", this.state.num); //打印的是2
})
this.setState({
num: 2,
})
}