概述
初入react框架,发了许多关于this的小错,这里总结一下:
首先,不管什么框架,都离不开js语言的限制,只要想清楚这是javaScript就能察觉你的错误是出现那儿的了。
在js语言中,关于this的指向,我总结为3句话:
- 谁调用的this就指向谁。
- es6箭头函数指向父层。
- 大部分你看不出谁调用的都是指向windows的
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
kk:false
}
}
componentDidMount() {
console.log(this);
this.timerID = setInterval(
() => this.tick(),
1000
);
}
click2(){
alert(2);
}
click1=()=>{
alert(1);
this.click2();
console.log(this.state.kk);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1 style={{backgroundColor:'red'}} onClick={this.click1}>Hello, world!</h1>
<h2 ref="h2" id="lala">It is {this.state.date.toLocaleTimeString()}.</h2>
<A/>
</div>
);
}
}
关注一下上面代码里面的几个this,基本上我项目里的所有情况都能概括了吧。html代码和生命周期函数里的this直接指向react的实例,click1函数的this本身是undefined,所以需要用箭头函数,指向父层,就是这个实例了
最后
以上就是大方小松鼠为你收集整理的react中的this指向的全部内容,希望文章能够帮你解决react中的this指向所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复