React 前端框架4

六、React 中的事件处理

(一)绑定事件的方式

在 React 中,事件绑定和传统的 HTML 中的事件绑定有一些不同,它采用了驼峰命名法来命名事件名称,并且事件绑定的属性值是一个函数。例如,在 HTML 中绑定点击事件可能是 <button onclick="handleClick()">点击我</button>,而在 React 中则是 <button onClick={() => handleClick()}>点击我</button>(这里假设 handleClick 是在组件内部定义的一个函数),或者更常见的是将函数先绑定到组件实例上(主要针对类组件),比如:

复制代码
import React, { Component } from 'react';

class ButtonComponent extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log('按钮被点击了');
  }

  render() {
    return (
      <button onClick={this.handleClick}>点击我</button>
    );
  }
}

export default ButtonComponent;

在类组件中,因为类的方法默认情况下 this 的指向问题,需要在 constructor 中通过 bind 方法将事件处理函数的 this 绑定到组件实例上,这样才能在事件处理函数中正确地访问到组件的属性和 state 等数据。

(二)事件参数传递

有时候我们需要在事件处理函数中传递额外的参数,常见的做法有两种:

  • 使用箭头函数包裹

    import React, { Component } from 'react';

    class ParameterPassingComponent extends Component {
    handleClick(name) {
    console.log(你好, ${name}!);
    }

    复制代码
    render() {
      return (
        <div>
          <button onClick={() => this.handleClick('小明')}>向小明打招呼</button>
          <button onClick={() => this.handleClick('小红')}>向小红打招呼</button>
        </div>
      );
    }

    }

    export default ParameterPassingComponent;

这里通过箭头函数包裹的方式,在调用 this.handleClick 时传递了不同的参数进去。

复制代码
import React, { Component } from 'react';

class ParameterPassingComponent extends Component {
  handleClick(name) {
    console.log(`你好, ${name}!`);
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick.bind(this, '小明')}>向小明打招呼</button>
        <button onClick={this.handleClick.bind(this, '小红')}>向小红打招呼</button>
      </div>
    );
  }
}

export default ParameterPassingComponent;

使用 bind 方法除了能绑定 this 之外,还可以同时传递其他参数,达到类似的效果。

相关推荐
产品研究员10 分钟前
AI生成可用的React交互代码实测:Lovable vs Stitch vs Paico
前端·react.js·aigc
biubiubiu_LYQ14 分钟前
入门开发者必学篇之JS事件循环:为什么你的代码输出总翻车?
前端·javascript
HwJack2023 分钟前
鸿蒙背景下 Cocos Creator 的三大 JS 引擎:JIT 与热更新的十字路口
javascript·华为·harmonyos
丷丩1 小时前
MapLibre GL JS第41课:向地图添加图标
前端·javascript·mapbox·maplibre gl js
掘金者阿豪1 小时前
终于!我的第二本书正式出版,吃透 Agentic AI 核心不踩坑
javascript·后端
三乐2281 小时前
事件循环是什么东西,一篇文章带你了解
前端·javascript
dy17172 小时前
二维码打印
前端·javascript·vue.js
智商不够_熬夜来凑2 小时前
【Radio & Checkbox】
前端·javascript·vue.js
xiaofeichaichai2 小时前
Diff 算法
前端·javascript
wgc2k3 小时前
Nest.js 基础-8-Hello,NestJS
开发语言·javascript·ecmascript