方法一,this可以通过缓存保存一份,从而拿到类的实例对象
抛砖引玉:
下面拿不到:
原因:
因为不是通过实例调用,所以此时的this已经不是指向实例了。所以this是undefined。所以变成undefined.study
指向全局的this,在严格模式下是undefined,而不是指向windows
通过实例调用的时候,this才是指向实例
原因:
解决方案:
1.在下图的32行代码上给原型添加一个changeWeather方法。
2.在25行代码把changeWeather方法挂载在实例自身上
this.xx = this.xxx,bind(this)
第36行的会优先调用自身的changeWeather方法。所以此时的this就是实例对象。
举一反三:
反例:
扩展,bind:
.bind方法返回一个新函数
案例1:
除了设置和更新state之外,你还可以为组件类定义方法。类方法通常需要使用this关键字,以便它可以访问方法中类的属性(例如state和props )。有几种方法可以让你的类方法访问this。
一种常见的方法是在构造函数中显式地绑定this,这样当组件初始化时,this就会绑定到类方法。你可能已经注意到上一个挑战使用了this.handleClick = this.handleClick.bind(this)用于其在构造函数中的handleClick方法。然后,当你在类方法中调用像this.setState()这样的函数时,this指的是这个类,而不是undefined。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
itemCount: 0
};
// change code below this line
this.addItem = this.addItem.bind(this)
// change code above this line
}
addItem() {
this.setState({
itemCount: this.state.itemCount + 1
});
}
render() {
return (
<div>
{ /* change code below this line */ }
<button onClick={this.addItem}>Click Me</button>
{ /* change code above this line */ }
<h1>Current Item Count: {this.state.itemCount}</h1>
</div>
);
}
};