import React from "react";
import "./styles.css";
class A extends React.Component {
constructor(props) {
super(props)
this.click1 = this.click.bind(this)
this.click2 = () => {console.log(this)}
}
click() {
console.log(this)
}
render() {
return (
<div>
<button onClick={this.click}>Click</button>
<button onClick={() => this.click()}>Click</button>
<button onClick={this.click1}>Click</button>
<button onClick={this.click2}>Click</button>
</div>
)
}
}
export default function App() {
return (
<div className="App">
<A />
</div>
);
}
依次点击4个按钮,控制台输出
undefined
A {props: Object, context: Object, refs: Object, updater: Object, click1: ƒ bound click()…}
A {props: Object, context: Object, refs: Object, updater: Object, click1: ƒ bound click()…}
A {props: Object, context: Object, refs: Object, updater: Object, click1: ƒ bound click()…}
第一种情况与 JavaScript 函数工作原理有关,this 最终是指向 window 的。
在 Class 组件中,事件绑定的正确姿势应该是这样 ⬇
传一个匿名函数给 onClick
click() {}
render() {
return (
<div>
<button onClick={() => this.click()}>Click</button>
</div>
)
}
用 bind 绑定 this
constructor(props) {
super(props)
this.click1 = this.click.bind(this)
}
click() {}
render() {
return (
<div>
<button onClick={this.click1}>Click</button>
</div>
)
}
用箭头函数定义
constructor(props) {
super(props)
this.click2 = () => {}
}
// 下面这种写法和在 constructor 中写 this.click2 = () => {} 是等价的
// click2 = () => {}
render() {
return (
<div>
<button onClick={this.click2}>Click</button>
</div>
)
}
在类中 click() {}
和 click = () => {}
两种写法的区别:
click() {}
是对象的共有属性(也就是原型上的属性)click = () => {}
是对象本身的属性
觉得 this 麻烦,那用函数组件就好啦 😊