事件的绑定和改变状态
-
handleClick 放在类 App 的原型对象上,供实例使用,在 render() 中调用时必须加 this。
import React from "react";
// 所有 React 组件必须像纯函数一样保护它的 props 不被更改
class App extends React.Component {
// 点击更改 state
constructor(props) {
super(props);
this.state = {isWash: false};
// 软连接,改变 this 指向
// 相当于 定义了一个新的函数变量,通过软连接,指向原型中的 handleClick,让 handleClick 和 App 的其他变量同级
this.handleClick = this.handleClick.bind(this)
}
render() {
// 打印指向 App 的对象
// handleClick 方法本来是定义在 App 原型之上的,直接打印 handleClick 会找不到,要 this.handleClick
console.log(this);
return (
<>
<button onClick={this.handleClick} style={{color: "blueviolet"}}>
请点击
</button>
<div>
老王今天 {this.state.isWash ? "去" : "没去"} 洗脚了
</div>
</>
)
};
handleClick() {
// console.log('点击了');
// 此时 this 为 undefined
console.log('handleClick->this', this);
// 修改 state 的唯一方法
this.setState({isWash: !this.state.isWash})
}
}
export default App
改变构造函数中的状态state
this.handleClick = this.handleClick.bind(this)
handleClick 要访问构造器的 state 就必须要改变 this 指向实例
-
handleClick 并不是通过实例调用的
-
类中的方法默认都开启了局部的严格模式,所以 handleClick this 为 undefined
类似:
const a = new App();
const r = a.click;
r();