笔记九、React组件的核心属性—事件处理(handleClick事件)

事件的绑定和改变状态

  • 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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElendaLee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值