问题出现:
我们在给比如按钮绑定点击事件函数的时候,我们在事件函数中使用this的时候会报错,这是由于this.xxx是undefined。
通过阅读了几篇博客之后我明白这并不是React这个框架的原因,这是JS的一个机制问题。
问题分析:
我们之前所知道的是,JS中对象调用方法的时候,方法中的this指向的是调用对象
1 2 3 4 5 6 7
| let obj = { tmp:'Yes!', testLog:function(){ console.log(this.tmp); } }; obj.testLog();
|
但是呢,如果我们使用一个指针指向该方法的内存区域,再通过这个指针调用这片内存的函数,就会发现this是windows
1 2 3 4 5 6 7 8
| let obj = { tmp:'Yes!', testLog:function(){ console.log(this.tmp); } }; let tmpLog = obj.testLog; tmpLog();
|
所以this.xxx就是windows.xxx是没有定义的。
而我们传递的事件函数就是一个函数,而onClick是一个中间变量这样就会导致this的指向丢失。
解决方法:
(1)构造函数绑定this(推荐)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Button extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(){ console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
|
(2)调用的时候绑定this
1 2 3 4 5 6 7 8 9 10 11 12
| class Button extends React.Component { handleClick(){ console.log('this is:', this); } render() { return ( <button onClick={this.handleClick.bind(this)}> Click me </button> ); } }
|
(3)箭头函数:箭头函数中的this只会固定的指向声明时的this指向。