• react合成事件——bind解决this指向——箭头函数解决this指向


    合成事件


    React合成事件是React模拟原生DOM事件所有能力的一个事件对象。根据 W3C规范来定义合成事件,兼容所有浏览器,拥有与浏览器原声事件相同的接口。合成事件除了拥有和浏览器原生事件相同的接口,包括stopPropagetion()和preventDefault()。
    在React中,所有事件都是合成的,不是原生DOM事件,可以通过 event.nativeEvent 属性获取原生DOM事件。合成事件不会映射到原生事件。
    浏览器兼容,实现更好的跨平台


    💕为什么出现这个技术?

    • 💖性能优化:使用事件代理统一接收原生事件的触发,从而可以使得真实 DOM 上不用绑定事件。React 挟持事件触发可以知道用户触发了什么事件,是通过什么原生事件调用的真实事件。这样可以通过对原生事件的优先级定义进而确定真实事件的优先级,再进而可以确定真实事件内触发的更新是什么优先级,最终可以决定对应的更新应该在什么时机更新。
    • 💖分层设计:解决跨平台问题,抹平浏览器差异和平台差异。

    使用事件函数和事件函数传参的三种用法

    import React, { Component } from 'react';
    
    class App extends Component {
        fn = (event)=>{console.log("fn",event);}
        fn1 = (msg)=>(event)=>{
            console.log("fn1",msg,event);
        }
        fn2 = (msg,event)=>{
            console.log(msg,event);
        }
        render() {
            return (
                <div>
                    <button onClick={this.fn}>+++</button>
                    <button onClick={this.fn1("第二种")}>+++</button>
                    <button onClick={(event)=>this.fn2("第三种",event)}>+++</button>
                </div>
            );
        }
    }
    
    export default App;
    

    在这里插入图片描述

    用bind解决this指向

    前一篇文章就说过,在react类组件中使用function成员属性,会找不见当前的this.
    在react事件绑定的类组件中,默认情况this指向会可能存在指向问题 undefined

    如果你写的此方案 方法名() 方案,用到 bind来绑定
    addNum() {
    	console.log(this.num++);
    }
    
    • 第一种方法:在执行类的构造函数,它只执行一次,初始化
    constructor(props) {
    	super(props);
    	this.addNum = this.addNum.bind(this)
    }
    
    • 第二种方法就是:函数直接绑定this
      在此处可以使用bind来绑定this指向,且还可以传参数
    <div>
    	<button onClick={this.addNum}>++</button>
    	<button onClick={this.addNum.bind(this,2)}>++</button>
    </div>
    

    箭头函数解决this的指向

    并且可以任意传入参数
    两种写法,一种写在视图层,一种写在控制层

    import React, { Component } from 'react';
    
    class App extends Component {
        num=100;
        addNum(evt){
            this.num++;
            this.forceUpdate();
        }
        addNum=(msg)=>(evt){
            this.num++;
            this.forceUpdate();
        }
        render() {
            return (
                <div>
                    <div><h1>{this.num}</h1></div>
                    <div>
                        <button onClick={(evt)=>this.addNum(evt,2)}>++</button>
                        <button onClick={this.addNum(2)}>++</button>
                    </div>
                </div>
            );
        }
    }
    
    export default App;
    
  • 相关阅读:
    Java9新增特性
    前端事件案例补充
    uni-app的生命周期
    第五十一天学习记录:C语言进阶:枚举和联合(共用体)
    Linux 文件系统Ramfs, rootfs and initramfs
    Flow深入浅出系列之使用Kotlin Flow自动刷新Android数据的策略
    074:vue+openlayers通过拖拽,旋转放缩地图(示例代码)
    从硬件结构到软件
    Java API访问HDFS
    SpringCloud-微服务架构演变
  • 原文地址:https://blog.csdn.net/m0_46672781/article/details/126958138