问题导入
import React from "react";
class ThisPoint extends React.Component {
fn1() {
console.log("fn1函数被调用", this); //这里的this指向是?
}
render() {
console.log(this); //这里的this指向是?
return (
<div>
<h1>thisPoint组件</h1>
<button onClick={this.fn1}>按钮</button>
</div>
);
}
}
export default ThisPoint;
用图说话。一个是当前组件,一个是undefined
分析原因
fn1函数被挂到了当前组件的原型上
解决方法
外层补充箭头函数
import React from "react";
class ThisPoint extends React.Component {
fn1() {
console.log("fn1函数被调用", this);
}
render() {
console.log(this);
return (
<div>
<h1>thisPoint组件</h1>
+ <button onClick={() => this.fn1()}>按钮</button>
</div>
);
}
}
export default ThisPoint;
箭头函数中的this指向外层作用域中的this
而render的this就是当前组件
bind改this
bind会生成一个新的函数,还会帮你改this
这里的this没有fn1,fn1在组件的原型上找到
constructor的this是当前组件,将这里的this通过bind传过去,fn1的this就成了constructor的this
import React from "react";
class ThisPoint extends React.Component {
constructor() {
super();
this.fn1 = this.fn1.bind(this);
}
fn1() {
console.log("fn1函数被调用", this);
}
render() {
console.log(this);
return (
<div>
<h1>thisPoint组件</h1>
<button onClick={this.fn1}>按钮</button>
</div>
);
}
}
export default ThisPoint;
this.fn1 = this.fn1.bind(this) 就是bind创建了一个新函数。
你用this.fn1接收了,
那么现在,this.fn1的this是和constructor一样的
指向当前组件
然后你就有了2个 fn1 函数
class实例方法
箭头函数中的this始终是该箭头函数所在作用域中的this
而箭头函数所在的作用域中的this指向当前组件
fn1 = () => {
console.log("fn1函数被调用", this);
};