”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > React:了解 React 的事件系统

React:了解 React 的事件系统

发布于2024-11-05
浏览:702

React: Understanding React

Overview of React's Event System

What is a Synthetic Event?

Synthetic events are an event-handling mechanism designed by React to achieve cross-browser compatibility, optimize performance, and simplify event handling. It encapsulates native browser events, providing a unified API and event handling approach, ensuring consistent event behavior across different browsers.

Working Principle of Synthetic Events

Event Delegation

React handles events through an event delegation mechanism. Event delegation means that React doesn't directly bind event listeners to each DOM element. Instead, it binds all event listeners to a single root node (usually the document or the root container of the application). When a user interacts with the page and triggers an event, the event bubbles up the DOM tree to the root node, where React captures the event and wraps it as a synthetic event.

Advantages of Event Delegation:

  • Performance Optimization: It reduces the number of event handlers that need to be bound, thereby lowering memory usage.

  • Simplified Event Management: By managing all events at the root node, React can more efficiently handle event propagation, prevent default behaviors, and perform other event-related operations.

Event Pooling

A key mechanism behind synthetic events is event pooling. Event pooling means that React reuses event objects instead of creating a new event object each time an event is triggered. When an event occurs, React takes an event object from the event pool, initializes it, and passes it to the event handler. After the event handling is complete, the event object is cleaned up and returned to the event pool for reuse in the next event.

Advantages of Event Pooling:

  • Reduced Memory Allocation: By reusing event objects, React avoids frequent memory allocation and garbage collection operations, which can significantly improve performance, especially for high-frequency events like mouse movements or scrolling.

Lifecycle of Synthetic Events

Due to event pooling, the lifecycle of synthetic events differs from that of native events. Typically, after the event handler function has finished executing, the properties of the synthetic event object are reset to null so that it can be returned to the pool for reuse.

Points to Note:

Asynchronous Operations: If you need to access the event object within an asynchronous operation, you must call the event.persist() method. This will prevent the event object from being returned to the pool, ensuring that it doesn't get reset during the asynchronous operation.

API and Usage of Synthetic Events

The React Synthetic Event API provides a set of interfaces similar to native browser events, which are commonly used in React. Below is a detailed introduction to some frequently used methods and properties, along with examples illustrating their usage scenarios.

a. preventDefault()

The preventDefault() method is used to prevent the default behavior of an event. Default behavior refers to the actions that the browser usually performs when an event occurs, such as refreshing the page when a form is submitted or navigating to a new page when a link is clicked.

Example: Preventing the default form submission behavior

function MyForm() {
  const handleSubmit = e => {
    e.preventDefault(); // Prevent the default form submission behavior
    console.log('Form submission prevented');
  };

  return (
    
); }

In this example, if preventDefault() is not called, clicking the submit button will trigger the form submission, causing the page to refresh. By calling preventDefault(), the default behavior is prevented, allowing you to customize the form handling logic instead.

b. stopPropagation()
The stopPropagation() method is used to stop the further propagation of an event. Events typically propagate from the target element where the event was triggered up to its parent elements (event bubbling). By calling stopPropagation(), you can prevent this propagation.

Example: Stopping the propagation of a click event

function Parent() {
  const handleParentClick = () => {
    console.log('Parent clicked');
  };

  return (
    
Parent Div
); } function Child() { const handleChildClick = e => { e.stopPropagation(); // Stop the event from bubbling up to the parent element console.log('Child clicked'); }; return ; }

In this example, clicking the button triggers the click event handler in the Child component. By default, the event would bubble up to the Parent component and trigger its click handler as well. However, by calling stopPropagation() in the Child component, the event bubbling to the Parent is prevented.

c. target
The target property refers to the actual DOM element that triggered the event. It is commonly used to access the element that initiated the event and to handle logic related to that element.

*Example: Accessing the element that triggered the event *

function MyComponent() {
  const handleClick = e => {
    console.log('Clicked element:', e.target);
  };

  return (
    
); }

In this example, when either button is clicked, the e.target in the handleClick function will point to the button element that was clicked. The target property is used to identify which specific element was clicked.

d. currentTarget
The currentTarget property refers to the DOM element to which the event handler is bound. During event handling, regardless of which child element the event bubbles to, currentTarget always points to the element that the event handler is attached to.

Example: Distinguishing between target and currentTarget

function MyComponent() {
  const handleClick = e => {
    console.log('Clicked element:', e.target);
    console.log('Event handler bound to:', e.currentTarget);
  };

  return (
    
); }

In this example, when any button is clicked, event.target will point to the button that was clicked, while event.currentTarget will always point to the parent div element where the event handler is bound.

e. persist()
The persist() method is used to retain the event object, preventing React from reusing it. This method is typically needed in asynchronous operations.

Example: Using the event object in an asynchronous operation

function MyComponent() {
  const handleClick = e => {
    e.persist(); // Retain the event object

    setTimeout(() => {
      console.log('Button clicked:', event.target);
    }, 1000);
  };

  return ;
}

In this example, because the event object might be reused in asynchronous operations, persist() is called to retain the event object, ensuring that the event properties can be safely accessed in the setTimeout callback.

React Synthetic Event Types

React provides various types of synthetic events that cover common user interaction scenarios. Below are some commonly used synthetic event types along with examples:

a. Mouse Events

  • onClick: Triggered when an element is clicked.

  • onDoubleClick: Triggered when an element is double-clicked.

  • onMouseDown: Triggered when a mouse button is pressed down on an element.

  • onMouseUp: Triggered when a mouse button is released on an element.

  • onMouseMove: Triggered when the mouse is moved over an element.

  • onMouseEnter: Triggered when the mouse pointer enters the element's area; does not bubble.

  • onMouseLeave: Triggered when the mouse pointer leaves the element's area; does not bubble.

Example: Using onClick and onMouseMove

function MouseTracker() {
  const handleMouseMove = e => {
    console.log(`Mouse position: (${e.clientX}, ${e.clientY})`);
  };

  return (
    
Move your mouse here
); } function MyApp() { return (
); }

In this example, the MouseTracker component logs the mouse position whenever it moves within the div area, while the button in the MyApp component logs a message when clicked.

b. Keyboard Events

  • onKeyDown: Triggered when a key is pressed down on the keyboard.

  • onKeyUp: Triggered when a key is released on the keyboard.

  • onKeyPress: Triggered when a key is pressed and held down (deprecated; it is recommended to use onKeyDown instead).

Example: Handling the onKeyDown Event

function KeyHandler() {
  const handleKeyDown = e => {
    console.log('Key pressed:', e.key);
  };

  return ;
}

In this example, when the user presses any key while focused on the input field, the handleKeyDown function logs the name of the pressed key.

c. Focus Events

  • onFocus: Triggered when an element gains focus.

  • onBlur: Triggered when an element loses focus.

Example: Handling onFocus and onBlur Events

function FocusExample() {
  return (
     console.log('Input focused')}
      onBlur={() => console.log('Input blurred')}
      placeholder="Focus and blur me"
    />
  );
}

In this example, when the input field gains or loses focus, a corresponding message is logged to the console.

d. Form Events

  • onChange: Triggered when the value of a form control changes.

  • onSubmit: Triggered when a form is submitted.

  • onInput: Triggered when the user inputs data (including actions like deleting or pasting).

Example: Handling onChange and onSubmit Events

function MyForm() {
  const [value, setValue] = React.useState('');

  const handleChange = e => {
    setValue(e.target.value);
  };

  const handleSubmit = e => {
    e.preventDefault();
    console.log('Form submitted with value:', value);
  };

  return (
    
); }

In this example, as the user types into the input field, the handleChange function updates the component's state. When the form is submitted, the handleSubmit function logs the current value of the input field.

Differences Between React Events and Regular HTML Events

a. Event Naming

  • Native: All lowercase (e.g., onclick).

  • React: CamelCase (e.g., onClick).

b. Event Handler Syntax

  • Native events use strings to specify event handlers.

  • React events use functions as event handlers.

c. Preventing Default Browser Behavior

  • Native: can use 'return false' to prevent the browser's default behavior.

  • React: Instead, you must explicitly call preventDefault() to achieve this.

d. Order of Event Execution
Native events execute first, followed by synthetic events. Synthetic events bubble up and are bound to the document. Therefore, it's advisable to avoid mixing native and synthetic events. If a native event stops propagation, it may prevent the synthetic event from executing because synthetic events rely on bubbling up to the document to execute.

Why does React Choose Synthetic Events

The reasons React chooses synthetic events include:

  • Cross-Browser Consistency: Synthetic events abstract away the differences in event handling across various browsers, ensuring consistent behavior across all browsers.

  • Performance Optimization: Event delegation and event pooling significantly reduce the overhead of event handling, improving the application's performance.

  • Better Event Management: With synthetic events, React can more effectively control event propagation, prevent default behaviors, and closely integrate with React's batch update mechanism for more efficient event handling.

版本声明 本文转载于:https://dev.to/lukewanghanxiang/react-understanding-reacts-event-system-dm7?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 评估机器学习分类模型
    评估机器学习分类模型
    大纲 模型评估的目标是什么? 模型评估的目的是什么,有哪些 常见的评估程序? 分类准确率有什么用,它的作用是什么 限制? 混淆矩阵如何描述一个 分类器? 可以从混淆矩阵计算哪些指标? T模型评估的目标是回答问题; 不同型号如何选择? 评估机器学习的过程有助于...
    编程 发布于2024-11-05
  • 如何消除 Eval-Base64_Decode PHP 病毒并保护您的网站?
    如何消除 Eval-Base64_Decode PHP 病毒并保护您的网站?
    如何像 PHP 病毒文件一样删除 Eval-Base64_Decode采用 eval-base64_decode 技术的病毒,例如您的病毒已经描述过,可能会很麻烦。我们将帮助您了解该病毒的性质及其潜在漏洞,并提供有关如何消除该病毒的全面指南。了解病毒此特定病毒用 eval-base64_decode...
    编程 发布于2024-11-05
  • 如何在 Serp 中排名 4
    如何在 Serp 中排名 4
    搜索引擎排名页面 (SERP) 是网站争夺可见性和流量的地方。到 2024 年,在 Google 和其他搜索引擎上的高排名仍然对在线成功至关重要。然而,SEO(搜索引擎优化)多年来已经发生了变化,并将继续发展。如果您想知道如何在 2024 年提高 SERP 排名,这里有一个简单的指南可以帮助您了解最...
    编程 发布于2024-11-05
  • 如何使用多处理在 Python 进程之间共享锁
    如何使用多处理在 Python 进程之间共享锁
    在 Python 中的进程之间共享锁当尝试使用 pool.map() 来定位具有多个参数(包括 Lock() 对象)的函数时,它是对于解决子进程之间共享锁的问题至关重要。由于 pickling 限制,传统的 multiprocessing.Lock() 无法直接传递给 Pool 方法。选项 1:使用...
    编程 发布于2024-11-05
  • Type Script 中 readonly 和 const 的区别
    Type Script 中 readonly 和 const 的区别
    这两个功能的相似之处在于它们都是不可分配的。 能具体解释一下吗? 在这篇文章中,我将分享它们之间的区别。 const 防止重新分配给变量。 在这种情况下,hisName 是一个不能重新分配的变量。 const hisName = 'Michael Scofield' hisName ...
    编程 发布于2024-11-05
  • 如何使用 Range 函数在 Python 中复制 C/C++ 循环语法?
    如何使用 Range 函数在 Python 中复制 C/C++ 循环语法?
    Python 中的 for 循环:扩展 C/C 循环语法在编程中,for 循环是迭代序列的基本结构。虽然 C/C 采用特定的循环初始化语法,但 Python 提供了更简洁的方法。不过,Python 中有一种模仿 C/C 循环风格的方法。实现循环操作:for (int k = 1; k <= c...
    编程 发布于2024-11-05
  • TechEazy Consulting 推出全面的 Java、Spring Boot 和 AWS 培训计划并提供免费实习机会
    TechEazy Consulting 推出全面的 Java、Spring Boot 和 AWS 培训计划并提供免费实习机会
    TechEazy Consulting 很高兴地宣布推出我们的综合培训计划,专为希望转向后端开发使用Java、Spring Boot的初学者、新手和专业人士而设计,以及 AWS。 此4个月的带薪培训计划之后是2个月的无薪实习,您可以在实际项目中应用您的新技能——无需任何额外的培训费用。对于那些希望填...
    编程 发布于2024-11-05
  • Polyfills——填充物还是缝隙? (第 1 部分)
    Polyfills——填充物还是缝隙? (第 1 部分)
    几天前,我们在组织的 Teams 聊天中收到一条优先消息,内容如下:发现安全漏洞 - 检测到 Polyfill JavaScript - HIGH。 举个例子,我在一家大型银行公司工作,你必须知道,银行和安全漏洞就像主要的敌人。因此,我们开始深入研究这个问题,并在几个小时内解决了这个问题,我将在下面...
    编程 发布于2024-11-05
  • 移位运算符和按位简写赋值
    移位运算符和按位简写赋值
    1。移位运算符 :向右移动。 >>>:无符号右移(零填充)。 2.移位运算符的一般语法 value > num-bits:将值位向右移动,保留符号位。 value >>> num-bits:通过在左侧插入零将值位向右移动。 3.左移 每次左移都会导致该值的所有位向左移动一位。 右侧插入0位。 效果:...
    编程 发布于2024-11-05
  • 如何使用 VBA 从 Excel 建立与 MySQL 数据库的连接?
    如何使用 VBA 从 Excel 建立与 MySQL 数据库的连接?
    VBA如何在Excel中连接到MySQL数据库?使用VBA连接到MySQL数据库尝试连接使用 VBA 在 Excel 中访问 MySQL 数据库有时可能具有挑战性。在您的情况下,您在尝试建立连接时遇到错误。要使用 VBA 成功连接到 MySQL 数据库,请按照下列步骤操作:Sub ConnectDB...
    编程 发布于2024-11-05
  • 测试自动化:使用 Java 和 TestNG 进行 Selenium 指南
    测试自动化:使用 Java 和 TestNG 进行 Selenium 指南
    测试自动化已成为软件开发过程中不可或缺的一部分,使团队能够提高效率、减少手动错误并以更快的速度交付高质量的产品。 Selenium 是一个用于自动化 Web 浏览器的强大工具,与 Java 的多功能性相结合,为构建可靠且可扩展的自动化测试套件提供了一个强大的框架。使用 Selenium Java 进...
    编程 发布于2024-11-05
  • 我对 DuckDuckGo 登陆页面的看法
    我对 DuckDuckGo 登陆页面的看法
    “你为什么不谷歌一下呢?”是我在对话中得到的常见答案。谷歌的无处不在甚至催生了新的动词“谷歌”。但是我编写的代码越多,我就越质疑我每天使用的数字工具。也许我对谷歌使用我的个人信息的方式不再感到满意。或者我们很多人依赖谷歌进行互联网搜索和其他应用程序,说实话,我厌倦了在搜索某个主题或产品后弹出的广告,...
    编程 发布于2024-11-05
  • 为什么 Turbo C++ 的“cin”只读取第一个字?
    为什么 Turbo C++ 的“cin”只读取第一个字?
    Turbo C 的“cin”限制:仅读取第一个单词在 Turbo C 中,“cin”输入运算符有一个处理字符数组时的限制。具体来说,它只会读取直到遇到空白字符(例如空格或换行符)。尝试读取多字输入时,这可能会导致意外行为。请考虑以下 Turbo C 代码:#include <iostream....
    编程 发布于2024-11-05
  • 使用 Buildpack 创建 Spring Boot 应用程序的 Docker 映像
    使用 Buildpack 创建 Spring Boot 应用程序的 Docker 映像
    介绍 您已经创建了一个 Spring Boot 应用程序。它在您的本地计算机上运行良好,现在您需要将该应用程序部署到其他地方。在某些平台上,您可以直接提交jar文件,它将被部署。在某些地方,您可以启动虚拟机,下载源代码,构建并运行它。但是,大多数时候您需要使用容器来部署应用程序。大...
    编程 发布于2024-11-05
  • 如何保护 PHP 代码免遭未经授权的访问?
    如何保护 PHP 代码免遭未经授权的访问?
    保护 PHP 代码免遭未经授权的访问保护 PHP 软件背后的知识产权对于防止其滥用或盗窃至关重要。为了解决这个问题,可以使用多种方法来混淆和防止未经授权的访问您的代码。一种有效的方法是利用 PHP 加速器。这些工具通过缓存频繁执行的部分来增强代码的性能。第二个好处是,它们使反编译和逆向工程代码变得更...
    编程 发布于2024-11-05

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3