【REACT-事件处理(event)和this指向】

REACT-事件处理(event)和this指向

import React, { Component,createRef } from 'react'
import ReactDOM from "react-dom";
export default class APP extends Component {
  name = "花花";

  /**
   * 面试常考题: 函数中的this指向
   * 1. 普通函数: function xxx(){}
   *      谁调用, 则this指向谁
   * 2. 箭头函数: ()=>{}
   *      不管谁调用, this指向声明时所在的区域
   * 3.REACT并不会真正的绑定一个事件到dom元素上,而是采用事件处理的模式
   */

  //  普通函数中的this, 指向调用者;
  _show(event) {
    // this应该是当前对象
    console.log(this.name,event);
  }

  // 箭头函数: 自带this绑定, 则不存在风险
  _show1 = (event) => {
    // 声明在 App 中,  this 就代表App
    console.log(this.name,event);
  };

  render() {
    return (
      <div>
        {/* 利用箭头函数保持this的特性, 代替 bind */}
        {/* 点击时 执行的是 箭头函数;  箭头函数 再执行其中的 this._show() */}
        <button onClick={(event) => this._show(event)}>箭头</button>
        {/* 完整格式:  语法糖 ()=> {return xxx;}  简化成 ()=> xxx */}

        <button onClick={this._show1}>箭头函数</button>
        {/* 例子: 点击时 打 亮亮的媳妇: 谁打? 是亮亮么? */}
        {/* 点击时, 调用 当前类(this)中的_show方法; 
        事件是window触发的; window触发的函数, this指向undefined */}

        {/* 页面刷新时, 绑定 当前对象this 到 _show 方法 */}
        <button onClick={this._show.bind(this)}>点击事件</button>
        {/* 
        不写bind: 点击时相当于 Window._show()
        写了bind: 点击时相当于 App._show()
        */}
      </div>
    );
  }
}
ReactDOM.render(
  // <React.StrictMode>
    <App/>
  // </React.StrictMode>
  ,document.getElementById('root'))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值