事件處理
React 文件處理事件 說明如何將事件處理常式附加到 React 元素。若要輸入這些事件處理常式,您可以使用 SyntheticEvent<T>
類型,如下所示
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}
5:29-5:48: Cannot call hook [1] because React hooks can only be called within components or hooks. [react-rule-hook]
還有更具體的合成事件類型,例如 SyntheticKeyboardEvent<T>
、SyntheticMouseEvent<T>
或 SyntheticTouchEvent<T>
。SyntheticEvent<T>
類型都採用單一類型引數:放置事件處理常式的 HTML 元素類型。
如果您不想新增元素實例的類型,也可以使用 SyntheticEvent
,不帶類型引數,如下所示:SyntheticEvent<>
。
注意:若要取得元素實例,例如上述範例中的
HTMLButtonElement
,常見的錯誤是使用event.target
,而不是event.currentTarget
。您要使用event.currentTarget
的原因是event.target
可能會因為 事件傳播 而成為錯誤的元素。
注意:React 使用其自己的事件系統,因此使用
SyntheticEvent
類型而不是 DOM 類型(例如Event
、KeyboardEvent
和MouseEvent
)非常重要。
React 提供的 SyntheticEvent<T>
類型及其相關的 DOM 事件為
SyntheticEvent<T>
for EventSyntheticAnimationEvent<T>
for AnimationEventSyntheticCompositionEvent<T>
for CompositionEventSyntheticInputEvent<T>
for InputEventSyntheticUIEvent<T>
for UIEventSyntheticFocusEvent<T>
for FocusEventSyntheticKeyboardEvent<T>
for KeyboardEventSyntheticMouseEvent<T>
for MouseEventSyntheticDragEvent<T>
for DragEventSyntheticWheelEvent<T>
for WheelEventSyntheticTouchEvent<T>
for TouchEventSyntheticTransitionEvent<T>
for TransitionEvent