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'))