react的事件处理

闲来无事,又重新看了一遍react的官网,趁机整理一些
在 JavaScript 中,class 的方法默认不会绑定 this。如果你忘记绑定 this.handleClick 并把它传入了 onClick,当你调用这个函数的时候 this 的值为 undefined。有以下几种可以解决这种情况

import React, { Component } from "react";

export default class Event extends Component {
  constructor() {
    super();
    this.state = {
      demo1: "确认",
      demo2: "确认",
      demo3: "确认",
      demo4: "确认",
      demo5: "5",
      demo6: "6",
    };
    //方法一:在此处绑定this
    this.handleClick1 = this.handleClick1.bind(this);
  }
  handleClick(key, value) {
    this.setState({
      [key]: value,
    });
  }
  //方法二:采用箭头函数
  handleClick1 = () => {
    this.handleClick("demo1", "取消");
  };
  handleClick2 = () => {
    this.handleClick("demo2", "取消");
  };
  handleClick3() {
    this.handleClick("demo3", "取消");
  }
  handleClick4() {
    this.handleClick("demo4", "取消");
  }
  deleteRow(val) {
    console.log("删除的数据",val);
  }
  render() {
    const { demo1, demo2, demo3, demo4, demo5, demo6 } = this.state;
    return (
      <div>
        <button onClick={this.handleClick1}>{demo1} </button>
        <button onClick={this.handleClick2}>{demo2} </button>
         //方法三:在DOM中采用箭头函数
        <button onClick={() => this.handleClick3()}>{demo3} </button>
        //方法四:改变this指向
        <button onClick={this.handleClick4.bind(this)}>{demo4} </button>
        {/* 给事件传递参数 */}
        //方法一:箭头函数
        <button onClick={() => this.deleteRow(demo5)}> 删除 </button>
        //方法二:改变this指向
        <button onClick={this.deleteRow.bind(this, demo6)}> Delete Row </button>
      </div>
    );
  }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值