所有內建瀏覽器元件,例如 <div>
,都支援一些常見的屬性和事件。
參考
常見元件(例如 <div>
)
<div className="wrapper">Some content</div>
Props
這些特殊的 React props 支援所有內建元件
-
children
:React 節點(元素、字串、數字、入口、空節點,例如null
、undefined
和布林值,或其他 React 節點的陣列)。指定元件內的內容。使用 JSX 時,通常會透過巢狀標籤(例如<div><span /></div>
)來隱含指定children
屬性。 -
dangerouslySetInnerHTML
:一個表單物件{ __html: '<p>some html</p>' }
內含原始 HTML 字串。覆寫 DOM 節點的innerHTML
屬性,並在內部顯示傳遞的 HTML。這應該非常小心地使用!如果內部的 HTML 不可信(例如,如果它基於使用者資料),您就有可能引入 XSS 漏洞。深入了解使用dangerouslySetInnerHTML
。 -
ref
:來自useRef
或createRef
的 ref 物件,或ref
回呼函式,或 舊版 ref 的字串。您的 ref 會填入此節點的 DOM 元素。深入了解如何使用 ref 來處理 DOM。 -
suppressContentEditableWarning
:布林值。如果為true
,會抑制 React 顯示的警告,針對同時具有children
和contentEditable={true}
(通常無法一起使用)的元素。如果您正在建置手動管理contentEditable
內容的文字輸入法庫,請使用此功能。 -
suppressHydrationWarning
:布林值。如果您使用 伺服器渲染,通常伺服器和用戶端呈現不同內容時會出現警告。在某些罕見情況下(例如時間戳記),很難或不可能保證完全匹配。如果您將suppressHydrationWarning
設定為true
,React 就不會警告您該元素的屬性和內容不符。它只會作用於一層,並旨在作為逃生艙口使用。不要過度使用它。 了解如何抑制水合錯誤。 -
style
: An object with CSS styles, for example{ fontWeight: 'bold', margin: 20 }
. Similarly to the DOMstyle
property, the CSS property names need to be written ascamelCase
, for examplefontWeight
instead offont-weight
. You can pass strings or numbers as values. If you pass a number, likewidth: 100
, React will automatically appendpx
(“pixels”) to the value unless it’s a unitless property. We recommend usingstyle
only for dynamic styles where you don’t know the style values ahead of time. In other cases, applying plain CSS classes withclassName
is more efficient. Read more aboutclassName
andstyle
.
這些標準 DOM 屬性也支援所有內建元件
accessKey
:字串。指定元素的鍵盤快速鍵。 一般不建議使用。aria-*
:ARIA 屬性讓您可以指定此元素的可存取性樹狀結構資訊。請參閱 ARIA 屬性 以取得完整參考。在 React 中,所有 ARIA 屬性名稱與 HTML 中完全相同。autoCapitalize
:字串。指定使用者輸入是否及如何大寫。className
:字串。指定元素的 CSS 類別名稱。進一步了解如何套用 CSS 樣式。contentEditable
:布林值。如果為true
,瀏覽器會讓使用者直接編輯呈現的元素。這用於實作富文字輸入程式庫,例如 Lexical。如果你嘗試將 React 子項傳遞給具有contentEditable={true}
的元素,React 會發出警告,因為 React 在使用者編輯後將無法更新其內容。data-*
:資料屬性讓你可以在元素附加一些字串資料,例如data-fruit="banana"
。在 React 中,它們並不常用,因為你通常會從 props 或狀態讀取資料。dir
:'ltr'
或'rtl'
。指定元素的文字方向。draggable
:布林值。指定元素是否可拖曳。HTML 拖放 API 的一部分。HTML 拖放 API。enterKeyHint
:字串。指定在虛擬鍵盤上為 Enter 鍵呈現哪個動作。htmlFor
: A string. For<label>
and<output>
, lets you associate the label with some control. Same asfor
HTML attribute. React uses the standard DOM property names (htmlFor
) instead of HTML attribute names.hidden
:布林值或字串。指定元素是否應隱藏。id
:字串。指定這個元素的唯一識別碼,可用於稍後尋找它或將它與其他元素連接。使用useId
產生它,以避免同一個元件的多個執行個體之間的衝突。is
:字串。如果指定,元件將會像 自訂元素 一樣運作。inputMode
:字串。指定要顯示哪種類型的鍵盤(例如,文字、數字或電話)。itemProp
:字串。指定元素對結構化資料爬蟲程式代表哪個屬性。lang
:字串。指定元素的語言。onAnimationEnd
:AnimationEvent
處理函式。當 CSS 動畫完成時觸發。onAnimationEndCapture
:onAnimationEnd
的版本,在 擷取階段 中觸發。onAnimationIteration
:AnimationEvent
處理函式。當 CSS 動畫的某個反覆動作結束,而另一個反覆動作開始時觸發。onAnimationIterationCapture
:onAnimationIteration
的版本,會在 擷取階段 觸發。onAnimationStart
:AnimationEvent
處理函式。在 CSS 動畫開始時觸發。onAnimationStartCapture
:onAnimationStart
,但會在 擷取階段 觸發。onAuxClick
:MouseEvent
處理函式。在非主要指標按鈕被按一下時觸發。onAuxClickCapture
:onAuxClick
的一個版本,會在 捕獲階段 觸發。onBeforeInput
:一個InputEvent
處理器 函式。在可編輯元素的值被修改之前觸發。React 尚未 使用原生beforeinput
事件,而是嘗試使用其他事件來進行多重填充。onBeforeInputCapture
:onBeforeInput
的一個版本,會在 捕獲階段 觸發。onBlur
:FocusEvent
處理常式函式。當元素失去焦點時觸發。與內建瀏覽器blur
事件不同,在 React 中,onBlur
事件會冒泡。onBlurCapture
:onBlur
的版本,會在 擷取階段 觸發。onClick
:一個MouseEvent
處理器 函式。當在指向裝置上按一下主要按鈕時觸發。onClickCapture
:onClick
的一個版本,會在 擷取階段 觸發。onCompositionStart
:CompositionEvent
處理常式函式。當輸入法編輯器開始新的組成階段時觸發。onCompositionStartCapture
:onCompositionStart
的版本,會在擷取階段觸發。onCompositionEnd
:CompositionEvent
處理常式函式。當輸入法編輯器完成或取消組成階段時觸發。onCompositionEndCapture
:onCompositionEnd
的一個版本,會在 擷取階段 中觸發。onCompositionUpdate
:CompositionEvent
處理函式。當 輸入法編輯器 接收新字元時觸發。onCompositionUpdateCapture
:onCompositionUpdate
的一個版本,會在 捕獲階段 觸發。onContextMenu
:MouseEvent
處理函式。當使用者嘗試開啟內容選單時觸發。onContextMenuCapture
:onContextMenu
的一個版本,會在 捕獲階段 觸發。onCopy
:一個ClipboardEvent
處理常式函數。當使用者嘗試將某個項目複製到剪貼簿時觸發。onCopyCapture
:onCopy
的一個版本,會在 擷取階段 觸發。onCut
:一個ClipboardEvent
處理常式函數。當使用者嘗試將某個項目剪下到剪貼簿時觸發。onCutCapture
:onCut
的版本,會在 擷取階段 觸發。onDoubleClick
:MouseEvent
處理常式 函式。使用者按兩下時觸發。對應到瀏覽器的dblclick
事件。onDoubleClickCapture
:onDoubleClick
的版本,會在 擷取階段 觸發。onDrag
:一個DragEvent
處理函式。在使用者拖曳某個東西時觸發。onDragCapture
:onDrag
的一個版本,會在 擷取階段 中觸發。onDragEnd
:DragEvent
處理常式函式。在使用者停止拖曳某個項目時觸發。onDragEndCapture
:onDragEnd
的版本,會在擷取階段觸發。onDragEnter
:DragEvent
處理常式函式。在拖曳的內容進入有效的放置目標時觸發。onDragEnterCapture
:onDragEnter
的一個版本,會在 擷取階段 觸發。onDragOver
:DragEvent
處理常式 函式。當拖曳的內容拖曳到有效的放置目標上時觸發。您必須在此呼叫e.preventDefault()
以允許放置。onDragOverCapture
:onDragOver
的一個版本,會在 擷取階段 觸發。onDragStart
:一個DragEvent
處理函式。當使用者開始拖曳元素時觸發。onDragStartCapture
:onDragStart
的一個版本,在 擷取階段 觸發。onDrop
:一個DragEvent
處理函式。當某個東西被放到有效的放置目標時觸發。onDropCapture
:onDrop
的一個版本,會在 捕獲階段 觸發。onFocus
:一個FocusEvent
處理函式。當元素接收焦點時觸發。與內建瀏覽器focus
事件不同,在 React 中,onFocus
事件會冒泡。onFocusCapture
:onFocus
的一個版本,會在 捕獲階段 觸發。onGotPointerCapture
:PointerEvent
處理函式。在元素以程式設計方式擷取指標時觸發。onGotPointerCaptureCapture
:onGotPointerCapture
的版本,會在 擷取階段 觸發。onKeyDown
:KeyboardEvent
處理函式。在按下鍵盤按鍵時觸發。onKeyDownCapture
:onKeyDown
的版本,會在 擷取階段 觸發。onKeyPress
:KeyboardEvent
處理常式函式。已棄用。請改用onKeyDown
或onBeforeInput
。onKeyPressCapture
:onKeyPress
的版本,會在 擷取階段 觸發。onKeyUp
:KeyboardEvent
處理常式函式。在按鍵放開時觸發。onKeyUpCapture
:onKeyUp
的版本,會在 擷取階段 觸發。onLostPointerCapture
:PointerEvent
處理常式 函式。當元素停止擷取指標時觸發。onLostPointerCaptureCapture
:onLostPointerCapture
的版本,會在 擷取階段 觸發。onMouseDown
:MouseEvent
處理常式。當指標按壓時觸發。onMouseDownCapture
:onMouseDown
的版本,在 擷取階段 觸發。onMouseEnter
:MouseEvent
處理常式。當指標移入元素內部時觸發。沒有擷取階段。相反地,onMouseLeave
和onMouseEnter
會從離開的元素傳播到進入的元素。onMouseLeave
:一個MouseEvent
處理函式。當指標移出元素外時觸發。沒有捕獲階段。相反地,onMouseLeave
和onMouseEnter
從離開的元素傳播到進入的元素。onMouseMove
:一個MouseEvent
處理函式。當指標改變座標時觸發。onMouseMoveCapture
:onMouseMove
的一個版本,會在 擷取階段 觸發。onMouseOut
:MouseEvent
處理器 函數。當指標移出元素外,或移入子元素時觸發。onMouseOutCapture
:onMouseOut
的一個版本,會在 擷取階段 觸發。onMouseUp
:MouseEvent
處理函式。當指標釋放時觸發。onMouseUpCapture
:onMouseUp
的版本,在擷取階段觸發。onPointerCancel
:PointerEvent
處理常式函數。在瀏覽器取消指標互動時觸發。onPointerCancelCapture
:onPointerCancel
的版本,在擷取階段觸發。onPointerDown
:PointerEvent
處理常式函數。在指標變為活動時觸發。onPointerDownCapture
:onPointerDown
的版本,在擷取階段觸發。onPointerEnter
:PointerEvent
處理常式函式。當指標移至元素內部時觸發。沒有擷取階段。相反地,onPointerLeave
和onPointerEnter
會從離開的元素傳播到進入的元素。onPointerLeave
:PointerEvent
處理常式函數。當指標移出元素外時觸發。沒有擷取階段。反之,onPointerLeave
和onPointerEnter
從離開的元素傳播到進入的元素。onPointerMove
:PointerEvent
處理常式函數。當指標變更座標時觸發。onPointerMoveCapture
:onPointerMove
的版本,於擷取階段中觸發。onPointerOut
:PointerEvent
處理函式。當指標移出元素時觸發,如果指標互動已取消,以及 其他一些原因。onPointerOutCapture
:onPointerOut
的版本,在 擷取階段 觸發。onPointerUp
:PointerEvent
處理函式。當指標不再作用中時觸發。onPointerUpCapture
:onPointerUp
的版本,會在 擷取階段 觸發。onPaste
:ClipboardEvent
處理常式 函式。當使用者嘗試從剪貼簿貼上某些內容時觸發。onPasteCapture
:onPaste
的版本,會在 擷取階段 觸發。onScroll
:事件
處理常式函式。當元素已捲動時觸發。此事件不會冒泡。onScrollCapture
:onScroll
的版本,在 擷取階段 中觸發。onSelect
:一個Event
處理器 函式。在可編輯元素(例如輸入)內的選取變更後觸發。React 擴充onSelect
事件,讓其也能用於contentEditable={true}
元素。此外,React 擴充它,讓其在空白選取和編輯(可能會影響選取)時觸發。onSelectCapture
:onSelect
的版本,會在 擷取階段 觸發。onTouchCancel
:一個TouchEvent
處理器 函式。在瀏覽器取消觸控互動時觸發。onTouchCancelCapture
:onTouchCancel
的一個版本,會在 擷取階段 觸發。onTouchEnd
:一個TouchEvent
處理常式 函式。在移除一個或多個觸控點時觸發。onTouchEndCapture
:onTouchEnd
的一個版本,會在 擷取階段 觸發。onTouchMove
:一個TouchEvent
處理常式 函式。在一個或多個觸控點移動時觸發。onTouchMoveCapture
:onTouchMove
的一個版本,會在 擷取階段 觸發。onTouchStart
:一個TouchEvent
處理常式 函式。當一個或多個觸控點被放置時觸發。onTouchStartCapture
:onTouchStart
的一個版本,會在 擷取階段 觸發。onTransitionEnd
:TransitionEvent
處理常式函式。在 CSS 轉場完成時觸發。onTransitionEndCapture
:onTransitionEnd
的一個版本,在 擷取階段 中觸發。onWheel
:WheelEvent
處理常式函式。在使用者旋轉滾輪按鈕時觸發。onWheelCapture
:onWheel
的一個版本,在 擷取階段 中觸發。角色
: 字串。明確指定元素角色供輔助技術使用。插槽
: 字串。使用 Shadow DOM 時指定插槽名稱。在 React 中,通常透過傳遞 JSX 作為 props 來達成等效模式,例如<Layout left={<Sidebar />} right={<Content />} />
。拼字檢查
: 布林值或 null。如果明確設定為true
或false
,則會啟用或停用拼字檢查。tabIndex
:數字。覆寫預設的 Tab 按鈕行為。避免使用-1
和0
以外的值。title
:字串。指定元素的工具提示文字。translate
:'yes'
或'no'
。傳遞'no'
會將元素內容排除在翻譯之外。
您也可以傳遞自訂屬性作為 props,例如 mycustomprop="someValue"
。這在與第三方程式庫整合時會很有用。自訂屬性名稱必須是小寫,且不能以 on
開頭。值會轉換為字串。如果您傳遞 null
或 undefined
,自訂屬性將會被移除。
這些事件只會觸發 <form>
元素
onReset
:一個Event
處理器 函式。當表單被重設時觸發。onResetCapture
:onReset
的一個版本,會在 擷取階段 觸發。onSubmit
:事件
處理器函式。當表單送出時觸發。onSubmitCapture
:onSubmit
的版本,會在 擷取階段 觸發。
這些事件僅對 <dialog>
元素觸發。與瀏覽器事件不同,它們會在 React 中冒泡
onCancel
:一個Event
處理函數。當使用者嘗試關閉對話方塊時觸發。onCancelCapture
:onCancel
的一個版本,會在 擷取階段 中觸發。onClose
:一個Event
處理函數。當對話方塊已關閉時觸發。onCloseCapture
:onClose
的一個版本,會在 擷取階段 中觸發。
這些事件僅會觸發 <details>
元素。與瀏覽器事件不同,它們會在 React 中冒泡
These events fire for <img>
, <iframe>
, <object>
, <embed>
, <link>
, and SVG <image>
elements. Unlike browser events, they bubble in React:
onLoad
:一個事件
處理函式。當資源載入時觸發。onLoadCapture
:onLoad
的一個版本,會在 擷取階段 觸發。onError
:一個事件
處理函式。當資源無法載入時觸發。onErrorCapture
:onError
的一個版本,會在 擷取階段 觸發。
這些事件會觸發資源,例如 <audio>
和 <video>
。與瀏覽器事件不同,它們會在 React 中冒泡
onAbort
:一個Event
處理器 函式。當資源尚未完全載入,但並非由於錯誤時觸發。onAbortCapture
:onAbort
的一個版本,會在 擷取階段 中觸發。onCanPlay
:一個事件
處理常式函數。當有足夠的資料開始播放,但不足以播放到結尾而不會緩衝時觸發。onCanPlayCapture
:onCanPlay
的一個版本,在 擷取階段 觸發。onCanPlayThrough
:一個事件
處理常式函數。當有足夠的資料,很可能可以開始播放,直到結尾都不會緩衝時觸發。onCanPlayThroughCapture
:onCanPlayThrough
的一個版本,會在 擷取階段 觸發。onDurationChange
:一個事件
處理常式 函式。當媒體持續時間已更新時觸發。onDurationChangeCapture
:onDurationChange
的一個版本,會在 擷取階段 觸發。onEmptied
:一個事件
處理常式 函式。當媒體已變為空白時觸發。onEmptiedCapture
:onEmptied
的一個版本,會在 擷取階段 觸發。onEncrypted
:一個Event
處理器 函式。當瀏覽器遇到加密媒體時觸發。onEncryptedCapture
:onEncrypted
的一個版本,會在 擷取階段 觸發。onEnded
:一個Event
處理器 函式。當播放停止,因為沒有東西可以播放時觸發。onEndedCapture
:onEnded
的版本,在 捕獲階段 觸發。onError
:一個事件
處理函式。當資源無法載入時觸發。onErrorCapture
:onError
的一個版本,會在 擷取階段 觸發。onLoadedData
:事件
處理常式函式。當目前的播放影格已載入時觸發。onLoadedDataCapture
:onLoadedData
的版本,在 捕獲階段 觸發。onLoadedMetadata
:事件
處理常式函式。當已載入媒體資訊時觸發。onLoadedMetadataCapture
:onLoadedMetadata
的版本,會在 擷取階段 觸發。onLoadStart
:事件
處理常式函式。在瀏覽器開始載入資源時觸發。onLoadStartCapture
:onLoadStart
的版本,會在 擷取階段 觸發。onPause
:一個Event
處理常式 函數。當媒體暫停時觸發。onPauseCapture
:onPause
的一個版本,在 擷取階段 中觸發。onPlay
:一個Event
處理常式 函數。當媒體不再暫停時觸發。onPlayCapture
:onPlay
的一個版本,在 擷取階段 中觸發。onPlaying
:一個Event
處理器 函式。當媒體開始或重新開始播放時觸發。onPlayingCapture
:一個onPlaying
版本,會在 擷取階段 觸發。onProgress
:一個Event
處理器 函式。資源載入期間會定期觸發。onProgressCapture
:onProgress
的版本,會在 擷取階段 中觸發。onRateChange
:事件
處理常式函式。在播放速率變更時觸發。onRateChangeCapture
:onRateChange
的版本,會在 擷取階段 中觸發。onResize
:事件
處理常式函式。在影片大小變更時觸發。onResizeCapture
:onResize
的版本,會在 擷取階段 觸發。onSeeked
:事件
處理常式函式。在搜尋作業完成時觸發。onSeekedCapture
:onSeeked
的版本,會在 擷取階段 觸發。onSeeking
:事件
處理常式函式。在搜尋作業開始時觸發。onSeekingCapture
:onSeeking
的一個版本,會在 擷取階段 中觸發。onStalled
:一個事件
處理器 函式。當瀏覽器正在等待資料,但資料卻一直無法載入時,就會觸發。onStalledCapture
:onStalled
的一個版本,會在 擷取階段 中觸發。onSuspend
:事件
處理常式函式。在資源載入暫停時觸發。onSuspendCapture
:onSuspend
的版本,在 擷取階段 觸發。onTimeUpdate
:事件
處理常式函式。在目前的播放時間更新時觸發。onTimeUpdateCapture
:onTimeUpdate
的版本,會在 擷取階段 觸發。onVolumeChange
:事件
處理常式函式。當音量變更時觸發。onVolumeChangeCapture
:onVolumeChange
的版本,會在 擷取階段 觸發。onWaiting
:事件
處理器函式。當播放因暫時缺乏資料而停止時觸發。onWaitingCapture
:onWaiting
的版本,會在 擷取階段 觸發。
注意事項
- 您無法同時傳遞
children
和dangerouslySetInnerHTML
。 - 有些事件(例如
onAbort
和onLoad
)不會在瀏覽器中冒泡,但在 React 中會冒泡。
ref
回呼函式
您可以將函式傳遞給 ref
屬性,而不是 ref 物件(例如 useRef
回傳的物件)。
<div ref={(node) => console.log(node)} />
當 <div>
DOM 節點新增至畫面時,React 會呼叫你的 ref
回呼,並將 DOM node
作為參數。當該 <div>
DOM 節點移除時,React 會呼叫你的 ref
回呼,並將 null
作為參數。
每當你傳遞一個不同的 ref
回呼時,React 也會呼叫你的 ref
回呼。在上方的範例中,(node) => { ... }
是在每次渲染時不同的函式。當你的元件重新渲染時,前一個函式會被呼叫,並將 null
作為參數,而下一個函式會被呼叫,並將 DOM 節點作為參數。
參數
node
:DOM 節點或null
。當 ref 附加時,React 會傳遞 DOM 節點給您,當 ref 分離時,傳遞null
。除非您在每次渲染時傳遞相同的函式參照給ref
回呼,否則回呼會在元件每次重新渲染時暫時分離並重新附加。
傳回
不要從 ref
回呼傳回任何東西。
React 事件物件
您的事件處理常式將會收到一個React 事件物件。它有時也稱為「合成事件」。
<button onClick={e => {
console.log(e); // React event object
}} />
它符合與基礎 DOM 事件相同的標準,但修正了一些瀏覽器的不一致性。
有些 React 事件不會直接對應到瀏覽器的原生事件。例如在 onMouseLeave
中,e.nativeEvent
將指向 mouseout
事件。具體對應關係不屬於公開 API 的一部分,且未來可能會變更。如果您出於某種原因需要基礎瀏覽器事件,請從 e.nativeEvent
中讀取它。
屬性
React 事件物件實作一些標準 Event
屬性
bubbles
: 布林值。傳回事件是否會在 DOM 中冒泡。cancelable
:一個布林值。傳回事件是否可以取消。currentTarget
:一個 DOM 節點。傳回 React 樹中附加目前處理程序的節點。defaultPrevented
:一個布林值。傳回是否已呼叫preventDefault
。eventPhase
:一個數字。傳回事件目前處於哪個階段。isTrusted
:一個布林值。傳回事件是否由使用者觸發。target
:一個 DOM 節點。傳回事件發生的節點(可能是遠端的子節點)。timeStamp
:一個數字。傳回事件發生的時間。
此外,React 事件物件提供下列屬性
nativeEvent
:一個 DOMEvent
。原始瀏覽器事件物件。
方法
React 事件物件實作一些標準 Event
方法
preventDefault()
:阻止瀏覽器的預設動作。stopPropagation()
:停止事件傳遞到 React 樹。
此外,React 事件物件提供以下方法
isDefaultPrevented()
:傳回一個布林值,表示是否呼叫preventDefault
。isPropagationStopped()
:傳回一個布林值,表示是否呼叫stopPropagation
。persist()
:不與 React DOM 搭配使用。使用 React Native 時,呼叫此函式可在事件發生後讀取事件的屬性。isPersistent()
:不與 React DOM 搭配使用。使用 React Native 時,傳回是否已呼叫persist
。
注意事項
currentTarget
、eventPhase
、target
和type
的值反映了 React 程式碼預期的值。在底層,React 會在根部附加事件處理常式,但這不會反映在 React 事件物件中。例如,e.currentTarget
可能與底層e.nativeEvent.currentTarget
不同。對於多型填充事件,e.type
(React 事件類型)可能與e.nativeEvent.type
(底層類型)不同。
AnimationEvent
處理常式函式
一個事件處理類型,用於 CSS 動畫 事件。
<div
onAnimationStart={e => console.log('onAnimationStart')}
onAnimationIteration={e => console.log('onAnimationIteration')}
onAnimationEnd={e => console.log('onAnimationEnd')}
/>
參數
e
:一個 React 事件物件,具有這些額外的AnimationEvent
屬性:
ClipboardEvent
處理函式
一個事件處理類型,用於 剪貼簿 API 事件。
<input
onCopy={e => console.log('onCopy')}
onCut={e => console.log('onCut')}
onPaste={e => console.log('onPaste')}
/>
參數
-
e
:一個 React 事件物件,具有這些額外的ClipboardEvent
屬性
CompositionEvent
處理函數
輸入法編輯器 (IME) 事件的事件處理類型 (IME)。
<input
onCompositionStart={e => console.log('onCompositionStart')}
onCompositionUpdate={e => console.log('onCompositionUpdate')}
onCompositionEnd={e => console.log('onCompositionEnd')}
/>
參數
e
:一個 React 事件物件,具備以下額外的CompositionEvent
屬性:
DragEvent
處理函式
HTML 拖放 API 事件的事件處理常式類型。
<>
<div
draggable={true}
onDragStart={e => console.log('onDragStart')}
onDragEnd={e => console.log('onDragEnd')}
>
Drag source
</div>
<div
onDragEnter={e => console.log('onDragEnter')}
onDragLeave={e => console.log('onDragLeave')}
onDragOver={e => { e.preventDefault(); console.log('onDragOver'); }}
onDrop={e => console.log('onDrop')}
>
Drop target
</div>
</>
參數
-
e
:一個 React 事件物件,具有這些額外的DragEvent
屬性它還包含繼承的
MouseEvent
屬性altKey
button
按鈕
ctrlKey
clientX
clientY
getModifierState(key)
metaKey
movementX
movementY
pageX
pageY
relatedTarget
screenX
screenY
shiftKey
它也包含繼承的
UIEvent
屬性
FocusEvent
處理函式
焦點事件的事件處理函式類型。
<input
onFocus={e => console.log('onFocus')}
onBlur={e => console.log('onBlur')}
/>
參數
-
e
:一個 React 事件物件,具有這些額外的FocusEvent
屬性它也包含繼承的
UIEvent
屬性
事件
處理函式
一般事件的事件處理類型。
參數
e
:React 事件物件,沒有其他屬性。
InputEvent
處理函數
onBeforeInput
事件的事件處理常式類型。
<input onBeforeInput={e => console.log('onBeforeInput')} />
參數
e
:React 事件物件,具有下列額外的InputEvent
屬性:
KeyboardEvent
處理函數
鍵盤事件的事件處理常式類型。
<input
onKeyDown={e => console.log('onKeyDown')}
onKeyUp={e => console.log('onKeyUp')}
/>
參數
-
e
:一個 React 事件物件,具有這些額外的KeyboardEvent
屬性altKey
charCode
code
ctrlKey
getModifierState(key)
key
keyCode
locale
metaKey
location
repeat
shiftKey
which
它也包含繼承的
UIEvent
屬性
MouseEvent
處理函式
滑鼠事件的事件處理常式。
<div
onClick={e => console.log('onClick')}
onMouseEnter={e => console.log('onMouseEnter')}
onMouseOver={e => console.log('onMouseOver')}
onMouseDown={e => console.log('onMouseDown')}
onMouseUp={e => console.log('onMouseUp')}
onMouseLeave={e => console.log('onMouseLeave')}
/>
參數
-
e
:一個 React 事件物件,具備這些額外的MouseEvent
屬性altKey
button
按鈕
ctrlKey
clientX
clientY
getModifierState(key)
metaKey
movementX
movementY
pageX
pageY
relatedTarget
screenX
screenY
shiftKey
它也包含繼承的
UIEvent
屬性
PointerEvent
處理函式
一個 指標事件 的事件處理類型。
<div
onPointerEnter={e => console.log('onPointerEnter')}
onPointerMove={e => console.log('onPointerMove')}
onPointerDown={e => console.log('onPointerDown')}
onPointerUp={e => console.log('onPointerUp')}
onPointerLeave={e => console.log('onPointerLeave')}
/>
參數
-
e
:一個 React 事件物件,具備下列額外的PointerEvent
屬性它還包含繼承的
MouseEvent
屬性altKey
button
按鈕
ctrlKey
clientX
clientY
getModifierState(key)
metaKey
movementX
movementY
pageX
pageY
relatedTarget
screenX
screenY
shiftKey
它也包含繼承的
UIEvent
屬性
TouchEvent
處理函式
事件處理類型,用於 觸控事件。
<div
onTouchStart={e => console.log('onTouchStart')}
onTouchMove={e => console.log('onTouchMove')}
onTouchEnd={e => console.log('onTouchEnd')}
onTouchCancel={e => console.log('onTouchCancel')}
/>
參數
-
e
:一個 React 事件物件,具備這些額外的TouchEvent
屬性它也包含繼承的
UIEvent
屬性
TransitionEvent
處理函式
CSS 轉場事件的事件處理類型。
<div
onTransitionEnd={e => console.log('onTransitionEnd')}
/>
參數
e
:一個 React 事件物件,具有這些額外的TransitionEvent
屬性:
UIEvent
處理函式
一般 UI 事件的事件處理常式類型。
<div
onScroll={e => console.log('onScroll')}
/>
參數
e
:一個 React 事件物件,具有這些額外的UIEvent
屬性:
WheelEvent
處理函式
事件處理類型為 onWheel
事件。
<div
onWheel={e => console.log('onWheel')}
/>
參數
-
e
:React 事件物件,具備下列額外的WheelEvent
屬性它還包含繼承的
MouseEvent
屬性altKey
button
按鈕
ctrlKey
clientX
clientY
getModifierState(key)
metaKey
movementX
movementY
pageX
pageY
relatedTarget
screenX
screenY
shiftKey
它也包含繼承的
UIEvent
屬性
用法
套用 CSS 樣式
在 React 中,您可以使用 className
指定 CSS 類別。它的作用類似於 HTML 中的 class
屬性
<img className="avatar" />
然後你在一個獨立的 CSS 檔案中為它撰寫 CSS 規則
/* In your CSS */
.avatar {
border-radius: 50%;
}
React 沒有規定你如何新增 CSS 檔案。在最簡單的情況下,你會在你的 HTML 中新增一個 <link>
標籤。如果你使用建置工具或框架,請參閱其文件以了解如何將 CSS 檔案新增到你的專案。
有時,樣式值取決於資料。使用 style
屬性來動態傳遞一些樣式
<img
className="avatar"
style={{
width: user.imageSize,
height: user.imageSize
}}
/>
在上述範例中,style={{}}
不是一個特殊的語法,而是一個常規的 {}
物件,位於 style={ }
JSX 大括號。 我們建議僅在你樣式取決於 JavaScript 變數時才使用 style
屬性。
export default function Avatar({ user }) { return ( <img src={user.imageUrl} alt={'Photo of ' + user.name} className="avatar" style={{ width: user.imageSize, height: user.imageSize }} /> ); }
深入探討
若要根據條件套用 CSS 類別,您需要使用 JavaScript 自行產生 className
字
例如,className={'row ' + (isSelected ? 'selected': '')}
將產生 className="row"
或 className="row selected"
,視 isSelected
是否為 true
而定。
若要讓這更具可讀性,您可以使用一個微型的輔助函式庫,例如 classnames
:
import cn from 'classnames';
function Row({ isSelected }) {
return (
<div className={cn('row', isSelected && 'selected')}>
...
</div>
);
}
如果您有多個條件式類別,這將特別方便
import cn from 'classnames';
function Row({ isSelected, size }) {
return (
<div className={cn('row', {
selected: isSelected,
large: size === 'large',
small: size === 'small',
})}>
...
</div>
);
}
使用 ref 操作 DOM 節點
有時,您需要取得與 JSX 中標籤相關聯的瀏覽器 DOM 節點。例如,當按一下按鈕時,如果您想要將焦點放在 <input>
上,您需要在瀏覽器 <input>
DOM 節點上呼叫 focus()
。
若要取得標籤的瀏覽器 DOM 節點,宣告一個 ref,並將其傳遞為該標籤的 ref
屬性
import { useRef } from 'react';
export default function Form() {
const inputRef = useRef(null);
// ...
return (
<input ref={inputRef} />
// ...
在 React 呈現在螢幕上後,它會將 DOM 節點放入 inputRef.current
中。
import { useRef } from 'react'; export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleClick}> Focus the input </button> </> ); }
閱讀更多關於 使用 refs 操縱 DOM 和 查看更多範例。
對於更進階的使用案例,ref
屬性也接受 回呼函式。
危險地設定內部 HTML
你可以將原始 HTML 字串傳遞給元素,如下所示
const markup = { __html: '<p>some raw html</p>' };
return <div dangerouslySetInnerHTML={markup} />;
這很危險。與底層 DOM innerHTML
屬性一樣,你必須非常小心!除非標記來自完全可信賴的來源,否則很容易以這種方式引入 XSS 漏洞。
例如,如果您使用將 Markdown 轉換為 HTML 的 Markdown 函式庫,您相信其剖析器不包含錯誤,且使用者只看到自己的輸入,您可以像這樣顯示產生的 HTML
import { Remarkable } from 'remarkable'; const md = new Remarkable(); function renderMarkdownToHTML(markdown) { // This is ONLY safe because the output HTML // is shown to the same user, and because you // trust this Markdown parser to not have bugs. const renderedHTML = md.render(markdown); return {__html: renderedHTML}; } export default function MarkdownPreview({ markdown }) { const markup = renderMarkdownToHTML(markdown); return <div dangerouslySetInnerHTML={markup} />; }
{__html}
物件應儘可能建立在 HTML 產生的附近,就像上述範例在 renderMarkdownToHTML
函式中所做的那樣。這可確保在您的程式碼中使用的所有原始 HTML 都明確標記為原始 HTML,而且只有您預期包含 HTML 的變數會傳遞給 dangerouslySetInnerHTML
。不建議像 <div dangerouslySetInnerHTML={{__html: markup}} />
一樣在內嵌中建立物件。
若要了解為什麼呈現任意 HTML 很危險,請將上述程式碼替換為以下內容
const post = {
// Imagine this content is stored in the database.
content: `<img src="" onerror='alert("you were hacked")'>`
};
export default function MarkdownPreview() {
// 🔴 SECURITY HOLE: passing untrusted input to dangerouslySetInnerHTML
const markup = { __html: post.content };
return <div dangerouslySetInnerHTML={markup} />;
}
嵌入在 HTML 中的程式碼會執行。駭客可能利用此安全漏洞竊取使用者資訊或執行使用者代碼的動作。僅使用 dangerouslySetInnerHTML
與受信任且已清除的資料。
處理滑鼠事件
此範例顯示一些常見的 滑鼠事件 及其觸發時機。
export default function MouseExample() { return ( <div onMouseEnter={e => console.log('onMouseEnter (parent)')} onMouseLeave={e => console.log('onMouseLeave (parent)')} > <button onClick={e => console.log('onClick (first button)')} onMouseDown={e => console.log('onMouseDown (first button)')} onMouseEnter={e => console.log('onMouseEnter (first button)')} onMouseLeave={e => console.log('onMouseLeave (first button)')} onMouseOver={e => console.log('onMouseOver (first button)')} onMouseUp={e => console.log('onMouseUp (first button)')} > First button </button> <button onClick={e => console.log('onClick (second button)')} onMouseDown={e => console.log('onMouseDown (second button)')} onMouseEnter={e => console.log('onMouseEnter (second button)')} onMouseLeave={e => console.log('onMouseLeave (second button)')} onMouseOver={e => console.log('onMouseOver (second button)')} onMouseUp={e => console.log('onMouseUp (second button)')} > Second button </button> </div> ); }
export default function PointerExample() { return ( <div onPointerEnter={e => console.log('onPointerEnter (parent)')} onPointerLeave={e => console.log('onPointerLeave (parent)')} style={{ padding: 20, backgroundColor: '#ddd' }} > <div onPointerDown={e => console.log('onPointerDown (first child)')} onPointerEnter={e => console.log('onPointerEnter (first child)')} onPointerLeave={e => console.log('onPointerLeave (first child)')} onPointerMove={e => console.log('onPointerMove (first child)')} onPointerUp={e => console.log('onPointerUp (first child)')} style={{ padding: 20, backgroundColor: 'lightyellow' }} > First child </div> <div onPointerDown={e => console.log('onPointerDown (second child)')} onPointerEnter={e => console.log('onPointerEnter (second child)')} onPointerLeave={e => console.log('onPointerLeave (second child)')} onPointerMove={e => console.log('onPointerMove (second child)')} onPointerUp={e => console.log('onPointerUp (second child)')} style={{ padding: 20, backgroundColor: 'lightblue' }} > Second child </div> </div> ); }
處理焦點事件
在 React 中,焦點事件會冒泡。你可以使用 currentTarget
和 relatedTarget
來區分聚焦或失焦事件是否來自於父元素外部。範例顯示如何偵測聚焦子元素、聚焦父元素,以及如何偵測焦點進入或離開整個子樹。
export default function FocusExample() { return ( <div tabIndex={1} onFocus={(e) => { if (e.currentTarget === e.target) { console.log('focused parent'); } else { console.log('focused child', e.target.name); } if (!e.currentTarget.contains(e.relatedTarget)) { // Not triggered when swapping focus between children console.log('focus entered parent'); } }} onBlur={(e) => { if (e.currentTarget === e.target) { console.log('unfocused parent'); } else { console.log('unfocused child', e.target.name); } if (!e.currentTarget.contains(e.relatedTarget)) { // Not triggered when swapping focus between children console.log('focus left parent'); } }} > <label> First name: <input name="firstName" /> </label> <label> Last name: <input name="lastName" /> </label> </div> ); }
export default function KeyboardExample() { return ( <label> First name: <input name="firstName" onKeyDown={e => console.log('onKeyDown:', e.key, e.code)} onKeyUp={e => console.log('onKeyUp:', e.key, e.code)} /> </label> ); }