」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > React:了解 React 的事件系統

React:了解 React 的事件系統

發佈於2024-11-05
瀏覽:699

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]刪除
最新教學 更多>
  • PHP陣列鍵值異常:了解07和08的好奇情況
    PHP陣列鍵值異常:了解07和08的好奇情況
    PHP數組鍵值問題,使用07&08 在給定數月的數組中,鍵值07和08呈現令人困惑的行為時,就會出現一個不尋常的問題。運行print_r($月份)返回意外結果:鍵“ 07”丟失,而鍵“ 08”分配給了9月的值。 此問題源於PHP對領先零的解釋。當一個數字帶有0(例如07或08)的前綴時,PHP...
    程式設計 發佈於2025-03-10
  • 如何從PHP中的數組中提取隨機元素?
    如何從PHP中的數組中提取隨機元素?
    從陣列中的隨機選擇,可以輕鬆從數組中獲取隨機項目。考慮以下數組:; 從此數組中檢索一個隨機項目,利用array_rand( array_rand()函數從數組返回一個隨機鍵。通過將$項目數組索引使用此鍵,我們可以從數組中訪問一個隨機元素。這種方法為選擇隨機項目提供了一種直接且可靠的方法。
    程式設計 發佈於2025-03-10
  • 為什麼我的CSS背景圖像出現?
    為什麼我的CSS背景圖像出現?
    故障排除:CSS背景圖像未出現 ,您的背景圖像儘管遵循教程說明,但您的背景圖像仍未加載。圖像和样式表位於相同的目錄中,但背景仍然是空白的白色帆布。 而不是不棄用的,您已經使用了CSS樣式: bockent {背景:封閉圖像文件名:背景圖:url(nickcage.jpg); 如果您的html,cs...
    程式設計 發佈於2025-03-10
  • 為什麼PYTZ最初顯示出意外的時區偏移?
    為什麼PYTZ最初顯示出意外的時區偏移?
    與pytz 最初從pytz獲得特定的偏移。例如,亞洲/hong_kong最初顯示一個七個小時37分鐘的偏移: 差異源利用本地化將時區分配給日期,使用了適當的時區名稱和偏移量。但是,直接使用DateTime構造器分配時區不允許進行正確的調整。 example pytz.timezone(&#...
    程式設計 發佈於2025-03-10
  • 為什麼儘管有效代碼,為什麼在PHP中捕獲輸入?
    為什麼儘管有效代碼,為什麼在PHP中捕獲輸入?
    在php ;?>" method="post">The intention is to capture the input from the text box and display it when the submit button is clicked.但是,輸出...
    程式設計 發佈於2025-03-10
  • 為什麼不使用CSS`content'屬性顯示圖像?
    為什麼不使用CSS`content'屬性顯示圖像?
    在Firefox extemers屬性為某些圖像很大,&& && && &&華倍華倍[華氏華倍華氏度]很少見,卻是某些瀏覽屬性很少,尤其是特定於Firefox的某些瀏覽器未能在使用內容屬性引用時未能顯示圖像的情況。這可以在提供的CSS類中看到:。 googlepic { 內容:url(&...
    程式設計 發佈於2025-03-10
  • 如何檢查對像是否具有Python中的特定屬性?
    如何檢查對像是否具有Python中的特定屬性?
    方法來確定對象屬性存在尋求一種方法來驗證對像中特定屬性的存在。考慮以下示例,其中嘗試訪問不確定屬性會引起錯誤: >>> a = someClass() >>> A.property Trackback(最近的最新電話): 文件“ ”,第1行, AttributeError: SomeClass...
    程式設計 發佈於2025-03-10
  • 在Java中使用for-to-loop和迭代器進行收集遍歷之間是否存在性能差異?
    在Java中使用for-to-loop和迭代器進行收集遍歷之間是否存在性能差異?
    For Each Loop vs. Iterator: Efficiency in Collection TraversalIntroductionWhen traversing a collection in Java, the choice arises between using a for-...
    程式設計 發佈於2025-03-10
  • 如何在Java字符串中有效替換多個子字符串?
    如何在Java字符串中有效替換多個子字符串?
    在java 中有效地替換多個substring,需要在需要替換一個字符串中的多個substring的情況下,很容易求助於重複應用字符串的刺激力量。 However, this can be inefficient for large strings or when working with nu...
    程式設計 發佈於2025-03-10
  • 如何克服PHP的功能重新定義限制?
    如何克服PHP的功能重新定義限制?
    克服PHP的函數重新定義限制在PHP中,多次定義一個相同名稱的函數是一個no-no。嘗試這樣做,如提供的代碼段所示,將導致可怕的“不能重新列出”錯誤。 但是,PHP工具腰帶中有一個隱藏的寶石:runkit擴展。它使您能夠靈活地重新定義函數。 runkit_function_renction_...
    程式設計 發佈於2025-03-10
  • 為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    mySQL錯誤#1089:錯誤的前綴鍵錯誤descript [#1089-不正確的前綴鍵在嘗試在表中創建一個prefix鍵時會出現。前綴鍵旨在索引字符串列的特定前綴長度長度,可以更快地搜索這些前綴。 了解prefix keys `這將在整個Movie_ID列上創建標準主鍵。主密鑰對於唯一識...
    程式設計 發佈於2025-03-10
  • 如何使用組在MySQL中旋轉數據?
    如何使用組在MySQL中旋轉數據?
    在關係數據庫中使用mySQL組使用mySQL組進行查詢結果,在關係數據庫中使用MySQL組,轉移數據的數據是指重新排列的行和列的重排以增強數據可視化。在這裡,我們面對一個共同的挑戰:使用組的組將數據從基於行的基於列的轉換為基於列。讓我們考慮以下查詢: select data d.data_ti...
    程式設計 發佈於2025-03-10
  • 大批
    大批
    [2 數組是對象,因此它們在JS中也具有方法。 切片(開始):在新數組中提取部分數組,而無需突變原始數組。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    程式設計 發佈於2025-03-10
  • 如何干淨地刪除匿名JavaScript事件處理程序?
    如何干淨地刪除匿名JavaScript事件處理程序?
    刪除匿名事件偵聽器將匿名事件偵聽器添加到元素中會提供靈活性和簡單性,但是當要刪除它們時,可以構成挑戰,而無需替換元素本身就可以替換一個問題。 element? element.addeventlistener(event,function(){/在這里工作/},false); 要解決此問題,請考...
    程式設計 發佈於2025-03-10

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3