首頁 > web前端 > js教程 > React:了解 React 的事件系統

React:了解 React 的事件系統

WBOY
發布: 2024-08-28 06:03:02
原創
314 人瀏覽過

React: Understanding React

React 事件系統概述

什麼是綜合事件?

合成事件是React設計的一種事件處理機制,旨在實現跨瀏覽器相容性、最佳化效能、簡化事件處理。 封裝原生瀏覽器事件,提供統一的API與事件處理方式,確保不同瀏覽器的事件行為一致。

綜合事件工作原理

活動委託

React 透過事件委託機制來處理事件。事件委託表示 React 不會直接將事件偵聽器綁定到每個 DOM 元素。相反,它將所有事件偵聽器綁定到單一根節點(通常是文件或應用程式的根容器)。當使用者與頁面互動並觸發事件時,該事件會在 DOM 樹中向上冒泡到根節點,React 會在根節點捕獲該事件並將其包裝為合成事件。

活動委託的優點:

  • 效能最佳化:減少了需要綁定的事件處理程序的數量,從而降低了記憶體使用量。

  • 簡化的事件管理:透過在根節點管理所有事件,React 可以更有效率地處理事件傳播、防止預設行為以及執行其他與事件相關的操作。

事件池

合成事件背後的關鍵機制是事件池。事件池意味著React重複使用事件對象,而不是每次觸發事件時建立一個新的事件對象。當事件發生時,React 從事件池中取出一個事件對象,對其進行初始化,然後將其傳遞給事件處理程序。事件處理完成後,事件物件被清理並返回到事件池中,以便在下一次事件中重複使用。

事件池的優點:

  • 減少記憶體分配:透過重複使用事件對象,React 避免了頻繁的記憶體分配和垃圾回收操作,這可以顯著提高效能,尤其是對於滑鼠移動或滾動等高頻事件。

綜合事件的生命週期

由於事件池的原因,合成事件的生命週期與原生事件不同。通常,事件處理函數執行完畢後,合成事件物件的屬性會重設為 null,以便可以將其傳回池中以供重用。

注意事項:

非同步操作:如果需要在非同步操作中存取事件對象,則必須呼叫 event.persist() 方法。這將防止事件物件返回到池中,確保它在非同步操作期間不會被重置。

綜合事件的 API 和使用

React Synthetic Event API 提供了一組類似於原生瀏覽器事件的接口,這些接口在 React 中常用。以下詳細介紹了一些常用的方法和屬性,並舉例說明了它們的使用情境。

a.預防預設()

preventDefault() 方法用來阻止事件的預設行為。預設行為是指瀏覽器在事件發生時通常執行的操作,例如提交表單時刷新頁面或點擊連結時導航到新頁面。

範例:阻止預設的表單提交行為

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

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="name" />
      <button type="submit">Submit</button>
    </form>
  );
}

登入後複製

在這個範例中,如果沒有呼叫preventDefault(),點擊提交按鈕會觸發表單提交,導致頁面刷新。透過呼叫preventDefault(),可以阻止預設行為,從而允許您自訂表單處理邏輯。

b. stopPropagation()
stopPropagation() 方法用於停止事件的進一步傳播。事件通常從觸發事件的目標元素傳播到其父元素(事件冒泡)。透過呼叫 stopPropagation(),您可以阻止這種傳播。

範例:停止傳播點擊事件

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

  return (
    <div onClick={handleParentClick}>
      Parent Div
      <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>;
}

登入後複製

在此範例中,按一下按鈕會觸發子元件中的按一下事件處理程序。預設情況下,該事件將向上冒泡到父組件並觸發其單擊處理程序。但是,透過在子元件中呼叫 stopPropagation() ,可以防止事件冒泡到父元件。

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: '200px', border: '1px solid black' }}>
      Move your mouse here
    </div>
  );
}

function MyApp() {
  return (
    <div>
      <button onClick={() => console.log('Button clicked!')}>Click Me</button>
      <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 (
    <form onSubmit={handleSubmit}>
      <input type="text" value={value} onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  );
}

登入後複製

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.事件執行順序
首先執行本機事件,然後執行合成事件。綜合事件冒泡並綁定到文件。因此,建議避免混合原生事件和合成事件。如果本機事件停止傳播,則可能會阻止合成事件執行,因為合成事件依賴冒泡到文件來執行。

為什麼 React 選擇合成事件

React 選擇合成事件的原因包括:

  • 跨瀏覽器一致性:綜合事件抽象化了不同瀏覽器之間事件處理的差異,確保所有瀏覽器之間的行為一致。

  • 效能最佳化:事件委託和事件池顯著降低了事件處理的開銷,提高了應用程式的效能。

  • 更好的事件管理:透過合成事件,React 可以更有效地控制事件傳播,防止預設行為,並與React 的批量更新機制緊密整合,以實現更高效的事件處理。

以上是React:了解 React 的事件系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板