search
HomeWeb Front-endJS TutorialReact: Understanding React&#s Event System

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 (
    <div onclick="{handleParentClick}">
      Parent Div
      <child></child>
    </div>
  );
}

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

  return <button onclick="{handleChildClick}">Click Me</button>;
}

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 (
    <div onclick="{handleClick}">
      <button>Button 1</button>
      <button>Button 2</button>
    </div>
  );
}

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 (
    <div onclick="{handleClick}">
      <button>Button 1</button>
      <button>Button 2</button>
    </div>
  );
}

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 <button onclick="{handleClick}">Click Me</button>;
}

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 (
    <div onmousemove="{handleMouseMove}" style="{{" height: border: solid black>
      Move your mouse here
    </div>
  );
}

function MyApp() {
  return (
    <div>
      <button onclick="{()"> console.log('Button clicked!')}>Click Me</button>
      <mousetracker></mousetracker>
    </div>
  );
}

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 <input type="text" onkeydown="{handleKeyDown}" placeholder="Press any key">;
}

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 (
    <input onfocus="{()"> 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.

The above is the detailed content of React: Understanding React&#s Event System. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

jQuery Check if Date is ValidjQuery Check if Date is ValidMar 01, 2025 am 08:51 AM

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

jQuery get element padding/marginjQuery get element padding/marginMar 01, 2025 am 08:53 AM

This article discusses how to use jQuery to obtain and set the inner margin and margin values ​​of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values ​​can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

10 jQuery Accordions Tabs10 jQuery Accordions TabsMar 01, 2025 am 01:34 AM

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

10 Worth Checking Out jQuery Plugins10 Worth Checking Out jQuery PluginsMar 01, 2025 am 01:29 AM

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

HTTP Debugging with Node and http-consoleHTTP Debugging with Node and http-consoleMar 01, 2025 am 01:37 AM

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

jquery add scrollbar to divjquery add scrollbar to divMar 01, 2025 am 01:30 AM

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.