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>
    );
  }
}

posted @ 2022-03-03 08:42  Cupid05  阅读(22)  评论(0编辑  收藏  举报