Skip to content

事件 Handling

Handling DOM 事件 in React, synthetic 事件, and 常见模式 for 用户 interaction.

你将学到

  • 如何 attach 事件处理函数 in JSX
  • Synthetic 事件 and React 事件系统
  • Passing 实参到 事件处理函数
  • Preventing 默认 behavior and 停止 propagation

概念讲解

Events in React

React handles events through a system called Synthetic Events. Instead of attaching real DOM event listeners to every element, React attaches a single listener at the root and delegates events. The event object you receive in a handler is a wrapper (SyntheticEvent) that behaves like the native DOM event but works identically across all browsers, eliminating cross-browser inconsistencies.

Attaching Handlers

In React, you attach event handlers as props using camelCase names: onClick, onChange, onSubmit, onMouseOver, etc. You pass a function reference (or inline arrow function) as the value. Unlike HTML attributes, you pass the function itself, not a string of code: onClick={handleClick} not onClick="handleClick()".

Passing Arguments

A common need is to pass extra arguments to an event handler. You have two options. The first is an inline arrow function: onClick={() => handleClick(id)}. The second is using bind: onClick={handleClick.bind(空, id)}. The arrow function approach is more readable and is the recommended pattern in modern React. Be aware that inline arrow functions create a new function on each render, which can have minor performance implications for very hot paths.

preventDefault and stopPropagation

To prevent a form from submitting or a link from navigating, call e.preventDefault() in the handler. To stop an event from bubbling up to parent elements, call e.stopPropagation(). These work exactly like their native DOM counterparts. For form submissions, always call preventDefault() first, then read the form data and handle it with your own logic.

Supported Event Types

React supports a wide range of events: clipboard (onCopy, onPaste), composition, keyboard (onKeyDown, onKeyPress, onKeyUp), focus (onFocus, onBlur), form (onChange, onInput, onSubmit), mouse (onClick, onDoubleClick, onMouseEnter), selection, touch, wheel, and media events. Each has a corresponding SyntheticEvent type. For custom events or non-standard DOM events, you can use native event listeners via refs and the useEffect hook to attach them manually to the DOM node.

示例代码

              import { useState } from "react";

function TodoList() {
  const [todos, setTodos] = useState(["Learn React", "Build an app"]);
  const [input, setInput] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault(); // Prevent page reload.
    if (!input.trim()) return;
    setTodos([...todos, input.trim()]);
    setInput("");
  };

  const removeTodo = (index) => {
    setTodos(todos.filter((_, i) => i !== index));
  };

  return (
    <form onSubmit={handleSubmit}>
      <input value={input} onChange={e => setInput(e.target.value)}
        placeholder="Add a todo" />
      <button type="submit">Add</button>
      <ul>
        {todos.map((todo, i) => (
          <li key={i}>
            {todo}
            <button onClick={() => removeTodo(i)}>Remove</button>
          </li>
        ))}
      </ul>
    </form>
  );
}
            

onSubmit calls preventDefault 到停止表单 reload. 移除 button uses inline arrow 到通过索引. onChange 更新输入状态 on 每个 keystroke.

动手试一试

  • Regex Tester

    验证表单输入使用 regular 表达式之前 handling 事件.

  • HTTP 状态 Codes

    理解状态 codes 当你的事件处理函数触发 API calls.

常见错误

错误写法

Calling 事件处理函数相反的 passing 它 as 引用

正确做法

编写 onClick={handleClick}, 不 onClick={handleClick()}. latter calls 函数 immediately 期间渲染. Use arrow 函数如果你 需要到 通过实参.

错误写法

Forgetting 到 call e.preventDefault() on 表单 submissions

正确做法

不使用 preventDefault, 浏览器将 reload page on 提交. 总是 call e.preventDefault() 首先 in 你的 onSubmit 处理函数, 然后处理表单数据.

练习 事件 Handling

8 个练习

练习 事件 Handling

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误