Skip to main content

事件处理

用于处理事件的 React 文档 展示了如何将事件处理程序附加到 React 元素。要键入这些事件处理程序,你可以使用 SyntheticEvent<T> 类型,如下所示:

¥The React docs for handling events show how an event handler can be attached to a React element. To type these event handlers you may use the SyntheticEvent<T> types like this:

1import {useState} from 'react';2import * as React from 'react';3
4function MyComponent(): React.Node {5  const [state, setState] = useState({count: 0});6
7  const handleClick = (event: SyntheticEvent<HTMLButtonElement>) => {8    // To access your button instance use `event.currentTarget`.9    event.currentTarget as HTMLButtonElement;10
11    setState(prevState => ({12      count: prevState.count + 1,13    }));14  };15
16  return (17    <div>18      <p>Count: {state.count}</p>19      <button onClick={handleClick}>Increment</button>20    </div>21  );22}

还有更具体的合成事件类型,例如 SyntheticKeyboardEvent<T>SyntheticMouseEvent<T>SyntheticTouchEvent<T>SyntheticEvent<T> 类型全部采用单一类型参数:事件处理程序所在的 HTML 元素的类型。

¥There are also more specific synthetic event types like SyntheticKeyboardEvent<T>, SyntheticMouseEvent<T>, or SyntheticTouchEvent<T>. The SyntheticEvent<T> types all take a single type argument: the type of the HTML element the event handler was placed on.

如果你不想添加元素实例的类型,你也可以使用不带类型参数的 SyntheticEvent,如下所示:SyntheticEvent<>

¥If you don't want to add the type of your element instance you can also use SyntheticEvent with no type arguments like so: SyntheticEvent<>.

注意:要获取元素实例,如上例中的 HTMLButtonElement,使用 event.target 而不是 event.currentTarget 是一个常见的错误。你想要使用 event.currentTarget 的原因是由于 事件传播event.target 可能是错误的元素。

¥Note: To get the element instance, like HTMLButtonElement in the example above, it is a common mistake to use event.target instead of event.currentTarget. The reason you want to use event.currentTarget is that event.target may be the wrong element due to event propagation.

注意:React 使用自己的事件系统,因此使用 SyntheticEvent 类型而不是 EventKeyboardEventMouseEvent 等 DOM 类型非常重要。

¥Note: React uses its own event system so it is important to use the SyntheticEvent types instead of the DOM types such as Event, KeyboardEvent, and MouseEvent.

React 提供的 SyntheticEvent<T> 类型以及它们相关的 DOM 事件有:

¥The SyntheticEvent<T> types that React provides and the DOM events they are related to are: