React的事件处理

React 元素的事件处理和 DOM 元素的很相似,但是有一点语法上的不同:

  • React 事件的命名采用小驼峰式(camelCase),而不是纯小写。
  • 使用 JSX 语法时你需要传入一个函数作为事件处理函数,而不是一个字符串。

原生DOM的写法:

<button onclick="handler">点击</button>

 React的写法:

<button onClick={this.handler}>点击</button>

在 React 中另一个不同点是你不能通过返回 false 的方式阻止默认行为。你必须显式的使用 preventDefault。

import React from "react";
class Event extends React.Component{
    handler(e){
        e.preventDefault();
        console.log("点击了");
    }
    render() {
        const element=<div>
            <button onClick={this.handler}>点击</button>
        </div>
        return element
    }
}
export default Event;

在React中的事件处理中,最重要的就是所绑定事件的this问题:

import React from "react";
class Event extends React.Component{
    handler(){
        console.log("this is" ,this);    //点击之后  this is undefined
    }
    render() {
        const element=<div>
            <button onClick={this.handler}>点击</button>
        </div>
        return element
    }
}
export default Event;

在 JavaScript 中,class 的方法默认不会绑定this,因此在handler方法中的this就是undefined。

如何解决这种情况:

1.在调用方法的时候直接使用bind改变其this的指向;

class Event extends React.Component{
    handler(){
        console.log("this is" ,this);
    }

    render() {
        const element=<div>
            <button onClick={this.handler.bind(this)}>点击</button>
        </div>
        return element
    }
}

2.在构造函数中对方法的this进行绑定;

class Event extends React.Component{
    constructor(props) {
        super(props);
        this.handler=this.handler.bind(this);
    }
    handler(){
        console.log("this is" ,this);
    }

    render() {
        const element=<div>
            <button onClick={this.handler}>点击</button>
        </div>
        return element
    }
}

3.将方法写成箭头函数

class Event extends React.Component{
    handler=()=>{
        console.log("this is" ,this);
    }

    render() {
        const element=<div>
            <button onClick={this.handler}>点击</button>
        </div>
        return element
    }
}

4.在调用的时候使用箭头函数

class Event extends React.Component{
    handler(){
        console.log("this is" ,this);
    }

    render() {
        const element=<div>
            <button onClick={event=>this.handler(event)}>点击</button>
        </div>
        return element
    }
}

四种方法的本质就是改变this的指向,前两种方法通过bind的形式改变this的指向,让其指向class类组件中的this。箭头函数的this指向箭头函数定义时所处的对象,而不是箭头函数使用时所在的对象,也就是说箭头函数在定义的时候就已经给它绑定的this,本质也是改变this的指向。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值