所有内置的浏览器组件,例如 <div>
,都支持一些常见的属性和事件。
¥All built-in browser components, such as <div>
, support some common props and events.
参考
¥Reference
常用组件(例如 <div>
)
¥Common components (e.g. <div>
)
<div className="wrapper">Some content</div>
属性
¥Props
所有内置组件都支持这些特殊的 React 属性:
¥These special React props are supported for all built-in components:
-
children
:一个 React 节点(一个元素、一个字符串、一个数字、一个门户, 一个空节点,如null
、undefined
和布尔值,或其他 React 节点的数组)。指定组件内部的内容。当你使用 JSX 时,你通常会通过像<div><span /></div>
这样的嵌套标签来隐式指定children
属性。¥
children
: A React node (an element, a string, a number, a portal, an empty node likenull
,undefined
and booleans, or an array of other React nodes). Specifies the content inside the component. When you use JSX, you will usually specify thechildren
prop implicitly by nesting tags like<div><span /></div>
. -
dangerouslySetInnerHTML
:{ __html: '<p>some html</p>' }
形式的对象,其中包含原始 HTML 字符串。覆盖 DOM 节点的innerHTML
属性,并在其中显示传递的 HTML。这应该非常小心地使用!如果内部的 HTML 不受信任(例如,如果它基于用户数据),你就有引入 XSS 漏洞的风险。阅读有关使用dangerouslySetInnerHTML
的更多信息。¥
dangerouslySetInnerHTML
: An object of the form{ __html: '<p>some html</p>' }
with a raw HTML string inside. Overrides theinnerHTML
property of the DOM node and displays the passed HTML inside. This should be used with extreme caution! If the HTML inside isn’t trusted (for example, if it’s based on user data), you risk introducing an XSS vulnerability. Read more about usingdangerouslySetInnerHTML
. -
ref
:来自useRef
或createRef
的引用对象,或ref
回调函数, 或 旧版引用。 的字符串 你的引用将填充此节点的 DOM 元素。阅读更多关于使用引用操作 DOM 的内容。¥
ref
: A ref object fromuseRef
orcreateRef
, or aref
callback function, or a string for legacy refs. Your ref will be filled with the DOM element for this node. Read more about manipulating the DOM with refs. -
suppressContentEditableWarning
:一个布尔值。如果是true
,则抑制 React 对同时具有children
和contentEditable={true}
(通常不能一起工作)的元素显示的警告。如果你正在构建手动管理contentEditable
内容的文本输入库,请使用此选项。¥
suppressContentEditableWarning
: A boolean. Iftrue
, suppresses the warning that React shows for elements that both havechildren
andcontentEditable={true}
(which normally do not work together). Use this if you’re building a text input library that manages thecontentEditable
content manually. -
suppressHydrationWarning
:一个布尔值。如果你正常使用 服务器渲染,,则当服务器和客户端渲染不同内容时会出现警告。在极少数情况下(如时间戳),很难或不可能保证完全匹配。如果你将suppressHydrationWarning
设置为true
,React 不会警告你该元素的属性和内容不匹配。它只能在一层深处工作,旨在用作应急方案。不要过度使用它。阅读有关抑制水合作用错误的信息。¥
suppressHydrationWarning
: A boolean. If you use server rendering, normally there is a warning when the server and the client render different content. In some rare cases (like timestamps), it is very hard or impossible to guarantee an exact match. If you setsuppressHydrationWarning
totrue
, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Don’t overuse it. Read about suppressing hydration errors. -
style
:具有 CSS 样式的对象,例如{ fontWeight: 'bold', margin: 20 }
。与 DOMstyle
属性类似,CSS 属性名称需要写成camelCase
,例如fontWeight
而不是font-weight
。你可以将字符串或数字作为值传递。如果你传递一个数字,比如width: 100
,React 会自动将px
(“pixels”) 附加到该值,除非它是 无单位的属性。。我们建议仅将style
用于你事先不知道样式值的动态样式。在其他情况下,使用className
应用纯 CSS 类会更有效。阅读有关className
和style
的更多信息。¥
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 属性:
¥These standard DOM props are also supported for all built-in components:
-
accessKey
:一个字符串。指定元素的键盘快捷键。一般不推荐。¥
accessKey
: A string. Specifies a keyboard shortcut for the element. Not generally recommended. -
aria-*
:ARIA 属性让你指定此元素的可访问性树信息。有关完整参考,请参阅 ARIA 属性。在 React 中,所有 ARIA 属性名称与 HTML 中完全相同。¥
aria-*
: ARIA attributes let you specify the accessibility tree information for this element. See ARIA attributes for a complete reference. In React, all ARIA attribute names are exactly the same as in HTML. -
autoCapitalize
:一个字符串。指定是否以及如何将用户输入大写。¥
autoCapitalize
: A string. Specifies whether and how the user input should be capitalized. -
className
:一个字符串。指定元素的 CSS 类名。阅读有关应用 CSS 样式的更多信息。¥
className
: A string. Specifies the element’s CSS class name. Read more about applying CSS styles. -
contentEditable
:一个布尔值。如果是true
,浏览器允许用户直接编辑渲染的元素。这用于实现像 词汇。 这样的富文本输入库,如果你尝试将 React 子级传递给具有contentEditable={true}
的元素,React 会发出警告,因为 React 将无法在用户编辑后更新其内容。¥
contentEditable
: A boolean. Iftrue
, the browser lets the user edit the rendered element directly. This is used to implement rich text input libraries like Lexical. React warns if you try to pass React children to an element withcontentEditable={true}
because React will not be able to update its content after user edits. -
data-*
:数据属性让你可以将一些字符串数据附加到元素,例如data-fruit="banana"
。在 React 中,它们并不常用,因为你通常会从属性或状态读取数据。¥
data-*
: Data attributes let you attach some string data to the element, for exampledata-fruit="banana"
. In React, they are not commonly used because you would usually read data from props or state instead. -
dir
:'ltr'
或'rtl'
。指定元素的文本方向。¥
dir
: Either'ltr'
or'rtl'
. Specifies the text direction of the element. -
draggable
:一个布尔值。指定元素是否可拖动。HTML 拖放 API。 的一部分¥
draggable
: A boolean. Specifies whether the element is draggable. Part of HTML Drag and Drop API. -
enterKeyHint
:一个字符串。指定为虚拟键盘上的回车键渲染的操作。¥
enterKeyHint
: A string. Specifies which action to present for the enter key on virtual keyboards. -
htmlFor
:一个字符串。对于<label>
和<output>
,让你 将标签与某些控件相关联。 和for
HTML 属性。 一样 React 使用标准的 DOM 属性名(htmlFor
)而不是 HTML 属性名。¥
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
:布尔值或字符串。指定元素是否应该隐藏。¥
hidden
: A boolean or a string. Specifies whether the element should be hidden. -
id
:一个字符串。指定此元素的唯一标识符,可用于以后查找它或将它与其他元素连接起来。使用useId
生成它以避免同一组件的多个实例之间发生冲突。¥
id
: A string. Specifies a unique identifier for this element, which can be used to find it later or connect it with other elements. Generate it withuseId
to avoid clashes between multiple instances of the same component. -
¥
is
: A string. If specified, the component will behave like a custom element. -
inputMode
:一个字符串。指定要显示的键盘类型(例如,文本、数字或调用)。¥
inputMode
: A string. Specifies what kind of keyboard to display (for example, text, number or telephone). -
itemProp
:一个字符串。指定该元素代表结构化数据爬虫的哪个属性。¥
itemProp
: A string. Specifies which property the element represents for structured data crawlers. -
lang
:一个字符串。指定元素的语言。¥
lang
: A string. Specifies the language of the element. -
onAnimationEnd
:一个AnimationEvent
处理程序 函数。当 CSS 动画完成时触发。¥
onAnimationEnd
: AnAnimationEvent
handler function. Fires when a CSS animation completes. -
onAnimationEndCapture
:在 捕获阶段。 中触发的onAnimationEnd
版本¥
onAnimationEndCapture
: A version ofonAnimationEnd
that fires in the capture phase. -
onAnimationIteration
:一个AnimationEvent
处理程序 函数。当一个 CSS 动画迭代结束,另一个迭代开始时触发。¥
onAnimationIteration
: AnAnimationEvent
handler function. Fires when an iteration of a CSS animation ends, and another one begins. -
onAnimationIterationCapture
:在 捕获阶段。 中触发的onAnimationIteration
版本¥
onAnimationIterationCapture
: A version ofonAnimationIteration
that fires in the capture phase. -
onAnimationStart
:一个AnimationEvent
处理程序 函数。当 CSS 动画开始时触发。¥
onAnimationStart
: AnAnimationEvent
handler function. Fires when a CSS animation starts. -
onAnimationStartCapture
:onAnimationStart
,但在 捕获阶段。 中触发¥
onAnimationStartCapture
:onAnimationStart
, but fires in the capture phase. -
onAuxClick
:MouseEvent
处理程序 函数。单击非主指针按钮时触发。¥
onAuxClick
: AMouseEvent
handler function. Fires when a non-primary pointer button was clicked. -
onAuxClickCapture
:在 捕获阶段。 中触发的onAuxClick
版本¥
onAuxClickCapture
: A version ofonAuxClick
that fires in the capture phase. -
onBeforeInput
:一个InputEvent
处理程序 函数。在修改可编辑元素的值之前触发。React 还没有使用原生的beforeinput
事件,而是尝试使用其他事件来填充它。¥
onBeforeInput
: AnInputEvent
handler function. Fires before the value of an editable element is modified. React does not yet use the nativebeforeinput
event, and instead attempts to polyfill it using other events. -
onBeforeInputCapture
:在 捕获阶段。 中触发的onBeforeInput
版本¥
onBeforeInputCapture
: A version ofonBeforeInput
that fires in the capture phase. -
onBlur
:FocusEvent
处理程序 函数。当元素失去焦点时触发。与浏览器内置的blur
事件不同,在 React 中onBlur
事件冒泡。¥
onBlur
: AFocusEvent
handler function. Fires when an element lost focus. Unlike the built-in browserblur
event, in React theonBlur
event bubbles. -
onBlurCapture
:在 捕获阶段。 中触发的onBlur
版本¥
onBlurCapture
: A version ofonBlur
that fires in the capture phase. -
onClick
:MouseEvent
处理程序 函数。在定点设备上单击主按钮时触发。¥
onClick
: AMouseEvent
handler function. Fires when the primary button was clicked on the pointing device. -
onClickCapture
:在 捕获阶段。 中触发的onClick
版本¥
onClickCapture
: A version ofonClick
that fires in the capture phase. -
onCompositionStart
:CompositionEvent
处理程序 函数。当 输入法编辑器 开始新的组合会话时触发。¥
onCompositionStart
: ACompositionEvent
handler function. Fires when an input method editor starts a new composition session. -
onCompositionStartCapture
:在 捕获阶段。 中触发的onCompositionStart
版本¥
onCompositionStartCapture
: A version ofonCompositionStart
that fires in the capture phase. -
onCompositionEnd
:CompositionEvent
处理程序 函数。当 输入法编辑器 完成或取消合成会话时触发。¥
onCompositionEnd
: ACompositionEvent
handler function. Fires when an input method editor completes or cancels a composition session. -
onCompositionEndCapture
:在 捕获阶段。 中触发的onCompositionEnd
版本¥
onCompositionEndCapture
: A version ofonCompositionEnd
that fires in the capture phase. -
onCompositionUpdate
:CompositionEvent
处理程序 函数。当 输入法编辑器 收到一个新角色时触发。¥
onCompositionUpdate
: ACompositionEvent
handler function. Fires when an input method editor receives a new character. -
onCompositionUpdateCapture
:在 捕获阶段。 中触发的onCompositionUpdate
版本¥
onCompositionUpdateCapture
: A version ofonCompositionUpdate
that fires in the capture phase. -
onContextMenu
:MouseEvent
处理程序 函数。当用户尝试打开上下文菜单时触发。¥
onContextMenu
: AMouseEvent
handler function. Fires when the user tries to open a context menu. -
onContextMenuCapture
:在 捕获阶段。 中触发的onContextMenu
版本¥
onContextMenuCapture
: A version ofonContextMenu
that fires in the capture phase. -
onCopy
:ClipboardEvent
处理程序 函数。当用户尝试将内容复制到剪贴板时触发。¥
onCopy
: AClipboardEvent
handler function. Fires when the user tries to copy something into the clipboard. -
onCopyCapture
:在 捕获阶段。 中触发的onCopy
版本¥
onCopyCapture
: A version ofonCopy
that fires in the capture phase. -
onCut
:ClipboardEvent
处理程序 函数。当用户尝试将内容剪切到剪贴板时触发。¥
onCut
: AClipboardEvent
handler function. Fires when the user tries to cut something into the clipboard. -
onCutCapture
:在 捕获阶段。 中触发的onCut
版本¥
onCutCapture
: A version ofonCut
that fires in the capture phase. -
onDoubleClick
:MouseEvent
处理程序 函数。当用户点击两次时触发。对应浏览器dblclick
事件。¥
onDoubleClick
: AMouseEvent
handler function. Fires when the user clicks twice. Corresponds to the browserdblclick
event. -
onDoubleClickCapture
:在 捕获阶段。 中触发的onDoubleClick
版本¥
onDoubleClickCapture
: A version ofonDoubleClick
that fires in the capture phase. -
onDrag
:DragEvent
处理程序 函数。当用户拖动某物时触发。¥
onDrag
: ADragEvent
handler function. Fires while the user is dragging something. -
onDragCapture
:在 捕获阶段。 中触发的onDrag
版本¥
onDragCapture
: A version ofonDrag
that fires in the capture phase. -
onDragEnd
:DragEvent
处理程序 函数。当用户停止拖动某物时触发。¥
onDragEnd
: ADragEvent
handler function. Fires when the user stops dragging something. -
onDragEndCapture
:在 捕获阶段。 中触发的onDragEnd
版本¥
onDragEndCapture
: A version ofonDragEnd
that fires in the capture phase. -
onDragEnter
:DragEvent
处理程序 函数。当拖动的内容进入有效的放置目标时触发。¥
onDragEnter
: ADragEvent
handler function. Fires when the dragged content enters a valid drop target. -
onDragEnterCapture
:在 捕获阶段。 中触发的onDragEnter
版本¥
onDragEnterCapture
: A version ofonDragEnter
that fires in the capture phase. -
onDragOver
:DragEvent
处理程序 函数。当拖动的内容被拖动到有效放置目标上时触发。你必须在此处调用e.preventDefault()
才能允许挂断。¥
onDragOver
: ADragEvent
handler function. Fires on a valid drop target while the dragged content is dragged over it. You must calle.preventDefault()
here to allow dropping. -
onDragOverCapture
:在 捕获阶段。 中触发的onDragOver
版本¥
onDragOverCapture
: A version ofonDragOver
that fires in the capture phase. -
onDragStart
:DragEvent
处理程序 函数。当用户开始拖动元素时触发。¥
onDragStart
: ADragEvent
handler function. Fires when the user starts dragging an element. -
onDragStartCapture
:在 捕获阶段。 中触发的onDragStart
版本¥
onDragStartCapture
: A version ofonDragStart
that fires in the capture phase. -
onDrop
:DragEvent
处理程序 函数。当某些东西落在有效的放置目标上时触发。¥
onDrop
: ADragEvent
handler function. Fires when something is dropped on a valid drop target. -
onDropCapture
:在 捕获阶段。 中触发的onDrop
版本¥
onDropCapture
: A version ofonDrop
that fires in the capture phase. -
onFocus
:FocusEvent
处理程序 函数。当元素获得焦点时触发。与浏览器内置的focus
事件不同,在 React 中onFocus
事件冒泡。¥
onFocus
: AFocusEvent
handler function. Fires when an element receives focus. Unlike the built-in browserfocus
event, in React theonFocus
event bubbles. -
onFocusCapture
:在 捕获阶段。 中触发的onFocus
版本¥
onFocusCapture
: A version ofonFocus
that fires in the capture phase. -
onGotPointerCapture
:PointerEvent
处理程序 函数。当元素以编程方式捕获指针时触发。¥
onGotPointerCapture
: APointerEvent
handler function. Fires when an element programmatically captures a pointer. -
onGotPointerCaptureCapture
:在 捕获阶段。 中触发的onGotPointerCapture
版本¥
onGotPointerCaptureCapture
: A version ofonGotPointerCapture
that fires in the capture phase. -
onKeyDown
:KeyboardEvent
处理程序 函数。按下某个键时触发。¥
onKeyDown
: AKeyboardEvent
handler function. Fires when a key is pressed. -
onKeyDownCapture
:在 捕获阶段。 中触发的onKeyDown
版本¥
onKeyDownCapture
: A version ofonKeyDown
that fires in the capture phase. -
onKeyPress
:KeyboardEvent
处理程序 函数。已弃用。请改用onKeyDown
或onBeforeInput
。¥
onKeyPress
: AKeyboardEvent
handler function. Deprecated. UseonKeyDown
oronBeforeInput
instead. -
onKeyPressCapture
:在 捕获阶段。 中触发的onKeyPress
版本¥
onKeyPressCapture
: A version ofonKeyPress
that fires in the capture phase. -
onKeyUp
:KeyboardEvent
处理程序 函数。释放键时触发。¥
onKeyUp
: AKeyboardEvent
handler function. Fires when a key is released. -
onKeyUpCapture
:在 捕获阶段。 中触发的onKeyUp
版本¥
onKeyUpCapture
: A version ofonKeyUp
that fires in the capture phase. -
onLostPointerCapture
:PointerEvent
处理程序 函数。当元素停止捕获指针时触发。¥
onLostPointerCapture
: APointerEvent
handler function. Fires when an element stops capturing a pointer. -
onLostPointerCaptureCapture
:在 捕获阶段。 中触发的onLostPointerCapture
版本¥
onLostPointerCaptureCapture
: A version ofonLostPointerCapture
that fires in the capture phase. -
onMouseDown
:MouseEvent
处理程序 函数。按下指针时触发。¥
onMouseDown
: AMouseEvent
handler function. Fires when the pointer is pressed down. -
onMouseDownCapture
:在 捕获阶段。 中触发的onMouseDown
版本¥
onMouseDownCapture
: A version ofonMouseDown
that fires in the capture phase. -
onMouseEnter
:MouseEvent
处理程序 函数。当指针在元素内移动时触发。没有捕获阶段。而是,onMouseLeave
和onMouseEnter
从被留下的元素传播到被输入的元素。¥
onMouseEnter
: AMouseEvent
handler function. Fires when the pointer moves inside an element. Does not have a capture phase. Instead,onMouseLeave
andonMouseEnter
propagate from the element being left to the one being entered. -
onMouseLeave
:MouseEvent
处理程序 函数。当指针移出元素时触发。没有捕获阶段。而是,onMouseLeave
和onMouseEnter
从被留下的元素传播到被输入的元素。¥
onMouseLeave
: AMouseEvent
handler function. Fires when the pointer moves outside an element. Does not have a capture phase. Instead,onMouseLeave
andonMouseEnter
propagate from the element being left to the one being entered. -
onMouseMove
:MouseEvent
处理程序 函数。当指针改变坐标时触发。¥
onMouseMove
: AMouseEvent
handler function. Fires when the pointer changes coordinates. -
onMouseMoveCapture
:在 捕获阶段。 中触发的onMouseMove
版本¥
onMouseMoveCapture
: A version ofonMouseMove
that fires in the capture phase. -
onMouseOut
:MouseEvent
处理程序 函数。当指针移出元素或移入子元素时触发。¥
onMouseOut
: AMouseEvent
handler function. Fires when the pointer moves outside an element, or if it moves into a child element. -
onMouseOutCapture
:在 捕获阶段。 中触发的onMouseOut
版本¥
onMouseOutCapture
: A version ofonMouseOut
that fires in the capture phase. -
onMouseUp
:MouseEvent
处理程序 函数。当指针被释放时触发。¥
onMouseUp
: AMouseEvent
handler function. Fires when the pointer is released. -
onMouseUpCapture
:在 捕获阶段。 中触发的onMouseUp
版本¥
onMouseUpCapture
: A version ofonMouseUp
that fires in the capture phase. -
onPointerCancel
:PointerEvent
处理程序 函数。当浏览器取消指针交互时触发。¥
onPointerCancel
: APointerEvent
handler function. Fires when the browser cancels a pointer interaction. -
onPointerCancelCapture
:在 捕获阶段。 中触发的onPointerCancel
版本¥
onPointerCancelCapture
: A version ofonPointerCancel
that fires in the capture phase. -
onPointerDown
:PointerEvent
处理程序 函数。当指针变为活动状态时触发。¥
onPointerDown
: APointerEvent
handler function. Fires when a pointer becomes active. -
onPointerDownCapture
:在 捕获阶段。 中触发的onPointerDown
版本¥
onPointerDownCapture
: A version ofonPointerDown
that fires in the capture phase. -
onPointerEnter
:PointerEvent
处理程序 函数。当指针在元素内移动时触发。没有捕获阶段。而是,onPointerLeave
和onPointerEnter
从被留下的元素传播到被输入的元素。¥
onPointerEnter
: APointerEvent
handler function. Fires when a pointer moves inside an element. Does not have a capture phase. Instead,onPointerLeave
andonPointerEnter
propagate from the element being left to the one being entered. -
onPointerLeave
:PointerEvent
处理程序 函数。当指针移出元素时触发。没有捕获阶段。而是,onPointerLeave
和onPointerEnter
从被留下的元素传播到被输入的元素。¥
onPointerLeave
: APointerEvent
handler function. Fires when a pointer moves outside an element. Does not have a capture phase. Instead,onPointerLeave
andonPointerEnter
propagate from the element being left to the one being entered. -
onPointerMove
:PointerEvent
处理程序 函数。当指针改变坐标时触发。¥
onPointerMove
: APointerEvent
handler function. Fires when a pointer changes coordinates. -
onPointerMoveCapture
:在 捕获阶段。 中触发的onPointerMove
版本¥
onPointerMoveCapture
: A version ofonPointerMove
that fires in the capture phase. -
onPointerOut
:PointerEvent
处理程序 函数。当指针移出元素时触发,如果指针交互被取消,并且 其他一些原因。¥
onPointerOut
: APointerEvent
handler function. Fires when a pointer moves outside an element, if the pointer interaction is cancelled, and a few other reasons. -
onPointerOutCapture
:在 捕获阶段。 中触发的onPointerOut
版本¥
onPointerOutCapture
: A version ofonPointerOut
that fires in the capture phase. -
onPointerUp
:PointerEvent
处理程序 函数。当指针不再活动时触发。¥
onPointerUp
: APointerEvent
handler function. Fires when a pointer is no longer active. -
onPointerUpCapture
:在 捕获阶段。 中触发的onPointerUp
版本¥
onPointerUpCapture
: A version ofonPointerUp
that fires in the capture phase. -
onPaste
:ClipboardEvent
处理程序 函数。当用户试图从剪贴板粘贴内容时触发。¥
onPaste
: AClipboardEvent
handler function. Fires when the user tries to paste something from the clipboard. -
onPasteCapture
:在 捕获阶段。 中触发的onPaste
版本¥
onPasteCapture
: A version ofonPaste
that fires in the capture phase. -
onScroll
:一个Event
处理程序 函数。滚动元素时触发。此事件不会冒泡。¥
onScroll
: AnEvent
handler function. Fires when an element has been scrolled. This event does not bubble. -
onScrollCapture
:在 捕获阶段。 中触发的onScroll
版本¥
onScrollCapture
: A version ofonScroll
that fires in the capture phase. -
onSelect
:一个Event
处理程序 函数。在可编辑元素内的选择(如输入更改)后触发。React 扩展了onSelect
事件以适用于contentEditable={true}
元素。此外,React 将其扩展为在空选择和编辑时触发(这可能会影响选择)。¥
onSelect
: AnEvent
handler function. Fires after the selection inside an editable element like an input changes. React extends theonSelect
event to work forcontentEditable={true}
elements as well. In addition, React extends it to fire for empty selection and on edits (which may affect the selection). -
onSelectCapture
:在 捕获阶段。 中触发的onSelect
版本¥
onSelectCapture
: A version ofonSelect
that fires in the capture phase. -
onTouchCancel
:TouchEvent
处理程序 函数。当浏览器取消触摸交互时触发。¥
onTouchCancel
: ATouchEvent
handler function. Fires when the browser cancels a touch interaction. -
onTouchCancelCapture
:在 捕获阶段。 中触发的onTouchCancel
版本¥
onTouchCancelCapture
: A version ofonTouchCancel
that fires in the capture phase. -
onTouchEnd
:TouchEvent
处理程序 函数。当一个或多个触摸点被移除时触发。¥
onTouchEnd
: ATouchEvent
handler function. Fires when one or more touch points are removed. -
onTouchEndCapture
:在 捕获阶段。 中触发的onTouchEnd
版本¥
onTouchEndCapture
: A version ofonTouchEnd
that fires in the capture phase. -
onTouchMove
:TouchEvent
处理程序 函数。触发一个或多个触摸点移动。¥
onTouchMove
: ATouchEvent
handler function. Fires one or more touch points are moved. -
onTouchMoveCapture
:在 捕获阶段。 中触发的onTouchMove
版本¥
onTouchMoveCapture
: A version ofonTouchMove
that fires in the capture phase. -
onTouchStart
:TouchEvent
处理程序 函数。当放置一个或多个触摸点时触发。¥
onTouchStart
: ATouchEvent
handler function. Fires when one or more touch points are placed. -
onTouchStartCapture
:在 捕获阶段。 中触发的onTouchStart
版本¥
onTouchStartCapture
: A version ofonTouchStart
that fires in the capture phase. -
onTransitionEnd
:TransitionEvent
处理程序 函数。当 CSS 转场完成时触发。¥
onTransitionEnd
: ATransitionEvent
handler function. Fires when a CSS transition completes. -
onTransitionEndCapture
:在 捕获阶段。 中触发的onTransitionEnd
版本¥
onTransitionEndCapture
: A version ofonTransitionEnd
that fires in the capture phase. -
onWheel
:WheelEvent
处理程序 函数。当用户旋转滚轮按钮时触发。¥
onWheel
: AWheelEvent
handler function. Fires when the user rotates a wheel button. -
onWheelCapture
:在 捕获阶段。 中触发的onWheel
版本¥
onWheelCapture
: A version ofonWheel
that fires in the capture phase. -
role
:一个字符串。为辅助技术明确指定元素角色。¥
role
: A string. Specifies the element role explicitly for assistive technologies. -
slot
:一个字符串。使用 shadow DOM 时指定插槽名称。在 React 中,通常通过将 JSX 作为属性传递来实现等效模式,例如<Layout left={<Sidebar />} right={<Content />} />
。¥
slot
: A string. Specifies the slot name when using shadow DOM. In React, an equivalent pattern is typically achieved by passing JSX as props, for example<Layout left={<Sidebar />} right={<Content />} />
. -
spellCheck
:布尔值或空值。如果明确设置为true
或false
,则启用或禁用拼写检查。¥
spellCheck
: A boolean or null. If explicitly set totrue
orfalse
, enables or disables spellchecking. -
tabIndex
:一个号码。覆盖默认的 Tab 按钮行为。避免使用-1
和0
以外的值。¥
tabIndex
: A number. Overrides the default Tab button behavior. Avoid using values other than-1
and0
. -
title
:一个字符串。指定元素的工具提示文本。¥
title
: A string. Specifies the tooltip text for the element. -
translate
:'yes'
或'no'
。传递'no'
会将元素内容排除在翻译之外。¥
translate
: Either'yes'
or'no'
. Passing'no'
excludes the element content from being translated.
你还可以将自定义属性作为属性传递,例如 mycustomprop="someValue"
。这在与第三方库集成时非常有用。自定义属性名称必须小写且不能以 on
开头。该值将被转换为字符串。如果你传递 null
或 undefined
,自定义属性将被删除。
¥You can also pass custom attributes as props, for example mycustomprop="someValue"
. This can be useful when integrating with third-party libraries. The custom attribute name must be lowercase and must not start with on
. The value will be converted to a string. If you pass null
or undefined
, the custom attribute will be removed.
这些事件仅针对 <form>
元素触发:
¥These events fire only for the <form>
elements:
-
onReset
:一个Event
处理程序 函数。当表单被重置时触发。¥
onReset
: AnEvent
handler function. Fires when a form gets reset. -
onResetCapture
:在 捕获阶段。 中触发的onReset
版本¥
onResetCapture
: A version ofonReset
that fires in the capture phase. -
onSubmit
:一个Event
处理程序 函数。提交表单时触发。¥
onSubmit
: AnEvent
handler function. Fires when a form gets submitted. -
onSubmitCapture
:在 捕获阶段。 中触发的onSubmit
版本¥
onSubmitCapture
: A version ofonSubmit
that fires in the capture phase.
这些事件仅针对 <dialog>
元素触发。与浏览器事件不同,它们在 React 中冒泡:
¥These events fire only for the <dialog>
elements. Unlike browser events, they bubble in React:
-
onCancel
:一个Event
处理程序 函数。当用户试图关闭对话框时触发。¥
onCancel
: AnEvent
handler function. Fires when the user tries to dismiss the dialog. -
onCancelCapture
:在 捕获阶段。 中触发的onCancel
版本¥
onCancelCapture
: A version ofonCancel
that fires in the capture phase. -
onClose
:一个Event
处理程序 函数。当对话框关闭时触发。¥
onClose
: AnEvent
handler function. Fires when a dialog has been closed. -
onCloseCapture
:在 捕获阶段。 中触发的onClose
版本¥
onCloseCapture
: A version ofonClose
that fires in the capture phase.
这些事件仅针对 <details>
元素触发。与浏览器事件不同,它们在 React 中冒泡:
¥These events fire only for the <details>
elements. Unlike browser events, they bubble in React:
-
onToggle
:一个Event
处理程序 函数。当用户切换详细信息时触发。¥
onToggle
: AnEvent
handler function. Fires when the user toggles the details. -
onToggleCapture
:在 捕获阶段。 中触发的onToggle
版本¥
onToggleCapture
: A version ofonToggle
that fires in the capture phase.
这些事件针对 <img>
、<iframe>
、<object>
、<embed>
、<link>
和 SVG <image>
元素触发。与浏览器事件不同,它们在 React 中冒泡:
¥These events fire for <img>
, <iframe>
, <object>
, <embed>
, <link>
, and SVG <image>
elements. Unlike browser events, they bubble in React:
-
onLoad
:一个Event
处理程序 函数。加载资源时触发。¥
onLoad
: AnEvent
handler function. Fires when the resource has loaded. -
onLoadCapture
:在 捕获阶段。 中触发的onLoad
版本¥
onLoadCapture
: A version ofonLoad
that fires in the capture phase. -
onError
:一个Event
处理程序 函数。当无法加载资源时触发。¥
onError
: AnEvent
handler function. Fires when the resource could not be loaded. -
onErrorCapture
:在 捕获阶段。 中触发的onError
版本¥
onErrorCapture
: A version ofonError
that fires in the capture phase.
这些事件会为 <audio>
和 <video>
等资源触发。与浏览器事件不同,它们在 React 中冒泡:
¥These events fire for resources like <audio>
and <video>
. Unlike browser events, they bubble in React:
-
onAbort
:一个Event
处理程序 函数。当资源没有完全加载时触发,但不是由于错误。¥
onAbort
: AnEvent
handler function. Fires when the resource has not fully loaded, but not due to an error. -
onAbortCapture
:在 捕获阶段。 中触发的onAbort
版本¥
onAbortCapture
: A version ofonAbort
that fires in the capture phase. -
onCanPlay
:一个Event
处理程序 函数。当有足够的数据开始播放,但又不足以在没有缓冲的情况下播放到结束时触发。¥
onCanPlay
: AnEvent
handler function. Fires when there’s enough data to start playing, but not enough to play to the end without buffering. -
onCanPlayCapture
:在 捕获阶段。 中触发的onCanPlay
版本¥
onCanPlayCapture
: A version ofonCanPlay
that fires in the capture phase. -
onCanPlayThrough
:一个Event
处理程序 函数。当有足够的数据可以开始播放而无需缓冲直到结束时触发。¥
onCanPlayThrough
: AnEvent
handler function. Fires when there’s enough data that it’s likely possible to start playing without buffering until the end. -
onCanPlayThroughCapture
:在 捕获阶段。 中触发的onCanPlayThrough
版本¥
onCanPlayThroughCapture
: A version ofonCanPlayThrough
that fires in the capture phase. -
onDurationChange
:一个Event
处理程序 函数。当媒体持续时间更新时触发。¥
onDurationChange
: AnEvent
handler function. Fires when the media duration has updated. -
onDurationChangeCapture
:在 捕获阶段。 中触发的onDurationChange
版本¥
onDurationChangeCapture
: A version ofonDurationChange
that fires in the capture phase. -
onEmptied
:一个Event
处理程序 函数。当媒体变空时触发。¥
onEmptied
: AnEvent
handler function. Fires when the media has become empty. -
onEmptiedCapture
:在 捕获阶段。 中触发的onEmptied
版本¥
onEmptiedCapture
: A version ofonEmptied
that fires in the capture phase. -
onEncrypted
:一个Event
处理程序 函数。当浏览器遇到加密媒体时触发。¥
onEncrypted
: AnEvent
handler function. Fires when the browser encounters encrypted media. -
onEncryptedCapture
:在 捕获阶段。 中触发的onEncrypted
版本¥
onEncryptedCapture
: A version ofonEncrypted
that fires in the capture phase. -
onEnded
:一个Event
处理程序 函数。当播放停止时触发,因为没有什么可以播放了。¥
onEnded
: AnEvent
handler function. Fires when the playback stops because there’s nothing left to play. -
onEndedCapture
:在 捕获阶段。 中触发的onEnded
版本¥
onEndedCapture
: A version ofonEnded
that fires in the capture phase. -
onError
:一个Event
处理程序 函数。当无法加载资源时触发。¥
onError
: AnEvent
handler function. Fires when the resource could not be loaded. -
onErrorCapture
:在 捕获阶段。 中触发的onError
版本¥
onErrorCapture
: A version ofonError
that fires in the capture phase. -
onLoadedData
:一个Event
处理程序 函数。当前播放帧已加载时触发。¥
onLoadedData
: AnEvent
handler function. Fires when the current playback frame has loaded. -
onLoadedDataCapture
:在 捕获阶段。 中触发的onLoadedData
版本¥
onLoadedDataCapture
: A version ofonLoadedData
that fires in the capture phase. -
onLoadedMetadata
:一个Event
处理程序 函数。加载元数据时触发。¥
onLoadedMetadata
: AnEvent
handler function. Fires when metadata has loaded. -
onLoadedMetadataCapture
:在 捕获阶段。 中触发的onLoadedMetadata
版本¥
onLoadedMetadataCapture
: A version ofonLoadedMetadata
that fires in the capture phase. -
onLoadStart
:一个Event
处理程序 函数。当浏览器开始加载资源时触发。¥
onLoadStart
: AnEvent
handler function. Fires when the browser started loading the resource. -
onLoadStartCapture
:在 捕获阶段。 中触发的onLoadStart
版本¥
onLoadStartCapture
: A version ofonLoadStart
that fires in the capture phase. -
onPause
:一个Event
处理程序 函数。媒体暂停时触发。¥
onPause
: AnEvent
handler function. Fires when the media was paused. -
onPauseCapture
:在 捕获阶段。 中触发的onPause
版本¥
onPauseCapture
: A version ofonPause
that fires in the capture phase. -
onPlay
:一个Event
处理程序 函数。当媒体不再暂停时触发。¥
onPlay
: AnEvent
handler function. Fires when the media is no longer paused. -
onPlayCapture
:在 捕获阶段。 中触发的onPlay
版本¥
onPlayCapture
: A version ofonPlay
that fires in the capture phase. -
onPlaying
:一个Event
处理程序 函数。当媒体开始或重新开始播放时触发。¥
onPlaying
: AnEvent
handler function. Fires when the media starts or restarts playing. -
onPlayingCapture
:在 捕获阶段。 中触发的onPlaying
版本¥
onPlayingCapture
: A version ofonPlaying
that fires in the capture phase. -
onProgress
:一个Event
处理程序 函数。在加载资源时定期触发。¥
onProgress
: AnEvent
handler function. Fires periodically while the resource is loading. -
onProgressCapture
:在 捕获阶段。 中触发的onProgress
版本¥
onProgressCapture
: A version ofonProgress
that fires in the capture phase. -
onRateChange
:一个Event
处理程序 函数。当播放速率改变时触发。¥
onRateChange
: AnEvent
handler function. Fires when playback rate changes. -
onRateChangeCapture
:在 捕获阶段。 中触发的onRateChange
版本¥
onRateChangeCapture
: A version ofonRateChange
that fires in the capture phase. -
onResize
:一个Event
处理程序 函数。当视频改变大小时触发。¥
onResize
: AnEvent
handler function. Fires when video changes size. -
onResizeCapture
:在 捕获阶段。 中触发的onResize
版本¥
onResizeCapture
: A version ofonResize
that fires in the capture phase. -
onSeeked
:一个Event
处理程序 函数。当查找操作完成时触发。¥
onSeeked
: AnEvent
handler function. Fires when a seek operation completes. -
onSeekedCapture
:在 捕获阶段。 中触发的onSeeked
版本¥
onSeekedCapture
: A version ofonSeeked
that fires in the capture phase. -
onSeeking
:一个Event
处理程序 函数。搜索操作开始时触发。¥
onSeeking
: AnEvent
handler function. Fires when a seek operation starts. -
onSeekingCapture
:在 捕获阶段。 中触发的onSeeking
版本¥
onSeekingCapture
: A version ofonSeeking
that fires in the capture phase. -
onStalled
:一个Event
处理程序 函数。当浏览器正在等待数据但一直未加载时触发。¥
onStalled
: AnEvent
handler function. Fires when the browser is waiting for data but it keeps not loading. -
onStalledCapture
:在 捕获阶段。 中触发的onStalled
版本¥
onStalledCapture
: A version ofonStalled
that fires in the capture phase. -
onSuspend
:一个Event
处理程序 函数。加载资源暂停时触发。¥
onSuspend
: AnEvent
handler function. Fires when loading the resource was suspended. -
onSuspendCapture
:在 捕获阶段。 中触发的onSuspend
版本¥
onSuspendCapture
: A version ofonSuspend
that fires in the capture phase. -
onTimeUpdate
:一个Event
处理程序 函数。当前播放时间更新时触发。¥
onTimeUpdate
: AnEvent
handler function. Fires when the current playback time updates. -
onTimeUpdateCapture
:在 捕获阶段。 中触发的onTimeUpdate
版本¥
onTimeUpdateCapture
: A version ofonTimeUpdate
that fires in the capture phase. -
onVolumeChange
:一个Event
处理程序 函数。当音量改变时触发。¥
onVolumeChange
: AnEvent
handler function. Fires when the volume has changed. -
onVolumeChangeCapture
:在 捕获阶段。 中触发的onVolumeChange
版本¥
onVolumeChangeCapture
: A version ofonVolumeChange
that fires in the capture phase. -
onWaiting
:一个Event
处理程序 函数。由于暂时缺少数据而停止播放时触发。¥
onWaiting
: AnEvent
handler function. Fires when the playback stopped due to temporary lack of data. -
onWaitingCapture
:在 捕获阶段。 中触发的onWaiting
版本¥
onWaitingCapture
: A version ofonWaiting
that fires in the capture phase.
注意事项
¥Caveats
-
你不能同时通过
children
和dangerouslySetInnerHTML
。¥You cannot pass both
children
anddangerouslySetInnerHTML
at the same time. -
有些事件(比如
onAbort
和onLoad
)不会在浏览器中冒泡,但会在 React 中冒泡。¥Some events (like
onAbort
andonLoad
) don’t bubble in the browser, but bubble in React.
ref
回调函数
¥ref
callback function
你可以将函数传递给 ref
属性,而不是引用对象(如 useRef
返回的对象)。
¥Instead of a ref object (like the one returned by useRef
), you may pass a function to the ref
attribute.
<div ref={(node) => console.log(node)} />
¥See an example of using the ref
callback.
当 <div>
DOM 节点被添加到屏幕时,React 将使用 DOM node
作为参数调用你的 ref
回调。当删除 <div>
DOM 节点时,React 将使用 null
调用你的 ref
回调。
¥When the <div>
DOM node is added to the screen, React will call your ref
callback with the DOM node
as the argument. When that <div>
DOM node is removed, React will call your ref
callback with null
.
每当你传递不同的 ref
回调时,React 也会调用你的 ref
回调。在上面的示例中,(node) => { ... }
在每个渲染器上都是不同的函数。当你的组件重新渲染时,前一个函数将以 null
作为参数被调用,下一个函数将以 DOM 节点被调用。
¥React will also call your ref
callback whenever you pass a different ref
callback. In the above example, (node) => { ... }
is a different function on every render. When your component re-renders, the previous function will be called with null
as the argument, and the next function will be called with the DOM node.
参数
¥Parameters
-
node
:一个 DOM 节点或null
。当引用连接时,React 会将 DOM 节点传递给你,当ref
分离时,React 会将null
传递给你。除非你在每次渲染时为ref
回调传递相同的函数引用,否则回调将在组件的每次重新渲染期间暂时分离并重新附加。¥
node
: A DOM node ornull
. React will pass you the DOM node when the ref gets attached, andnull
when theref
gets detached. Unless you pass the same function reference for theref
callback on every render, the callback will get temporarily detached and re-attached during every re-render of the component.
React 事件对象
¥React event object
你的事件处理程序将收到一个 React 事件对象。有时也称为 “合成事件”。
¥Your event handlers will receive a React event object. It is also sometimes known as a “synthetic event”.
<button onClick={e => {
console.log(e); // React event object
}} />
它符合与底层 DOM 事件相同的标准,但修复了一些浏览器不一致的问题。
¥It conforms to the same standard as the underlying DOM events, but fixes some browser inconsistencies.
一些 React 事件不直接映射到浏览器的原生事件。比如在 onMouseLeave
中,e.nativeEvent
会指向一个 mouseout
事件。具体映射不是公共 API 的一部分,将来可能会发生变化。如果出于某种原因需要底层浏览器事件,请阅读 e.nativeEvent
。
¥Some React events do not map directly to the browser’s native events. For example in onMouseLeave
, e.nativeEvent
will point to a mouseout
event. The specific mapping is not part of the public API and may change in the future. If you need the underlying browser event for some reason, read it from e.nativeEvent
.
属性
¥Properties
React 事件对象实现了一些标准的 Event
属性:
¥React event objects implement some of the standard Event
properties:
-
bubbles
:一个布尔值。返回事件是否通过 DOM 冒泡。¥
bubbles
: A boolean. Returns whether the event bubbles through the DOM. -
cancelable
:一个布尔值。返回事件是否可以取消。¥
cancelable
: A boolean. Returns whether the event can be canceled. -
currentTarget
:一个 DOM 节点。返回当前处理程序在 React 树中附加到的节点。¥
currentTarget
: A DOM node. Returns the node to which the current handler is attached in the React tree. -
defaultPrevented
:一个布尔值。返回preventDefault
是否被调用。¥
defaultPrevented
: A boolean. Returns whetherpreventDefault
was called. -
eventPhase
:一个号码。返回事件当前处于哪个阶段。¥
eventPhase
: A number. Returns which phase the event is currently in. -
isTrusted
:一个布尔值。返回事件是否由用户发起。¥
isTrusted
: A boolean. Returns whether the event was initiated by user. -
target
:一个 DOM 节点。返回事件发生的节点(可能是远方的子级)。¥
target
: A DOM node. Returns the node on which the event has occurred (which could be a distant child). -
timeStamp
:一个号码。返回事件发生的时间。¥
timeStamp
: A number. Returns the time when the event occurred.
此外,React 事件对象提供以下属性:
¥Additionally, React event objects provide these properties:
方法
¥Methods
React 事件对象实现了一些标准的 Event
方法:
¥React event objects implement some of the standard Event
methods:
-
preventDefault()
:阻止事件的默认浏览器操作。¥
preventDefault()
: Prevents the default browser action for the event. -
stopPropagation()
:通过 React 树停止事件传播。¥
stopPropagation()
: Stops the event propagation through the React tree.
此外,React 事件对象提供了这些方法:
¥Additionally, React event objects provide these methods:
-
isDefaultPrevented()
:返回一个布尔值,指示是否调用了preventDefault
。¥
isDefaultPrevented()
: Returns a boolean value indicating whetherpreventDefault
was called. -
isPropagationStopped()
:返回一个布尔值,指示是否调用了stopPropagation
。¥
isPropagationStopped()
: Returns a boolean value indicating whetherstopPropagation
was called. -
persist()
:不与 React DOM 一起使用。使用 React Native,在事件发生后调用它来读取事件的属性。¥
persist()
: Not used with React DOM. With React Native, call this to read event’s properties after the event. -
isPersistent()
:不与 React DOM 一起使用。使用 React Native,返回是否已调用persist
。¥
isPersistent()
: Not used with React DOM. With React Native, returns whetherpersist
has been called.
注意事项
¥Caveats
-
currentTarget
、eventPhase
、target
和type
的值反映了你的 React 代码期望的值。在幕后,React 在根部附加了事件处理程序,但这并没有反映在 React 事件对象中。例如,e.currentTarget
可能与基础e.nativeEvent.currentTarget
不同。对于 polyfilled 事件,e.type
(React 事件类型)可能不同于e.nativeEvent.type
(底层类型)。¥The values of
currentTarget
,eventPhase
,target
, andtype
reflect the values your React code expects. Under the hood, React attaches event handlers at the root, but this is not reflected in React event objects. For example,e.currentTarget
may not be the same as the underlyinge.nativeEvent.currentTarget
. For polyfilled events,e.type
(React event type) may differ frome.nativeEvent.type
(underlying type).
AnimationEvent
处理函数
¥AnimationEvent
handler function
CSS 动画 事件的事件处理程序类型。
¥An event handler type for the CSS animation events.
<div
onAnimationStart={e => console.log('onAnimationStart')}
onAnimationIteration={e => console.log('onAnimationIteration')}
onAnimationEnd={e => console.log('onAnimationEnd')}
/>
参数
¥Parameters
-
e
:具有这些额外AnimationEvent
属性的 React 事件对象:¥
e
: A React event object with these extraAnimationEvent
properties:
ClipboardEvent
处理函数
¥ClipboardEvent
handler function
剪贴板 API 事件的事件处理程序类型。
¥An event handler type for the Clipboard API events.
<input
onCopy={e => console.log('onCopy')}
onCut={e => console.log('onCut')}
onPaste={e => console.log('onPaste')}
/>
参数
¥Parameters
-
e
:具有这些额外ClipboardEvent
属性的 React 事件对象:¥
e
: A React event object with these extraClipboardEvent
properties:
CompositionEvent
处理函数
¥CompositionEvent
handler function
输入法编辑器 (IME) 事件的事件处理程序类型。
¥An event handler type for the input method editor (IME) events.
<input
onCompositionStart={e => console.log('onCompositionStart')}
onCompositionUpdate={e => console.log('onCompositionUpdate')}
onCompositionEnd={e => console.log('onCompositionEnd')}
/>
参数
¥Parameters
-
e
:具有这些额外CompositionEvent
属性的 React 事件对象:¥
e
: A React event object with these extraCompositionEvent
properties:
DragEvent
处理函数
¥DragEvent
handler function
HTML 拖放 API 事件的事件处理程序类型。
¥An event handler type for the HTML Drag and Drop API events.
<>
<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>
</>
参数
¥Parameters
-
e
:具有这些额外DragEvent
属性的 React 事件对象:¥
e
: A React event object with these extraDragEvent
properties:它还包括继承的
MouseEvent
属性:¥It also includes the inherited
MouseEvent
properties:它还包括继承的
UIEvent
属性:¥It also includes the inherited
UIEvent
properties:
FocusEvent
处理函数
¥FocusEvent
handler function
焦点事件的事件处理程序类型。
¥An event handler type for the focus events.
<input
onFocus={e => console.log('onFocus')}
onBlur={e => console.log('onBlur')}
/>
参数
¥Parameters
-
e
:具有这些额外FocusEvent
属性的 React 事件对象:¥
e
: A React event object with these extraFocusEvent
properties:它还包括继承的
UIEvent
属性:¥It also includes the inherited
UIEvent
properties:
Event
处理函数
¥Event
handler function
通用事件的事件处理程序类型。
¥An event handler type for generic events.
参数
¥Parameters
-
e
:没有附加属性的 React 事件对象。¥
e
: A React event object with no additional properties.
InputEvent
处理函数
¥InputEvent
handler function
onBeforeInput
事件的事件处理程序类型。
¥An event handler type for the onBeforeInput
event.
<input onBeforeInput={e => console.log('onBeforeInput')} />
参数
¥Parameters
-
e
:具有这些额外InputEvent
属性的 React 事件对象:¥
e
: A React event object with these extraInputEvent
properties:
KeyboardEvent
处理函数
¥KeyboardEvent
handler function
键盘事件的事件处理程序类型。
¥An event handler type for keyboard events.
<input
onKeyDown={e => console.log('onKeyDown')}
onKeyUp={e => console.log('onKeyUp')}
/>
参数
¥Parameters
-
e
:具有这些额外KeyboardEvent
属性的 React 事件对象:¥
e
: A React event object with these extraKeyboardEvent
properties:它还包括继承的
UIEvent
属性:¥It also includes the inherited
UIEvent
properties:
MouseEvent
处理函数
¥MouseEvent
handler function
鼠标事件的事件处理程序类型。
¥An event handler type for mouse events.
<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')}
/>
参数
¥Parameters
-
e
:具有这些额外MouseEvent
属性的 React 事件对象:¥
e
: A React event object with these extraMouseEvent
properties:它还包括继承的
UIEvent
属性:¥It also includes the inherited
UIEvent
properties:
PointerEvent
处理函数
¥PointerEvent
handler function
指针事件。 的事件处理程序类型
¥An event handler type for pointer events.
<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')}
/>
参数
¥Parameters
-
e
:具有这些额外PointerEvent
属性的 React 事件对象:¥
e
: A React event object with these extraPointerEvent
properties:它还包括继承的
MouseEvent
属性:¥It also includes the inherited
MouseEvent
properties:它还包括继承的
UIEvent
属性:¥It also includes the inherited
UIEvent
properties:
TouchEvent
处理函数
¥TouchEvent
handler function
触摸事件。 的事件处理程序类型
¥An event handler type for touch events.
<div
onTouchStart={e => console.log('onTouchStart')}
onTouchMove={e => console.log('onTouchMove')}
onTouchEnd={e => console.log('onTouchEnd')}
onTouchCancel={e => console.log('onTouchCancel')}
/>
参数
¥Parameters
-
e
:具有这些额外TouchEvent
属性的 React 事件对象:¥
e
: A React event object with these extraTouchEvent
properties:它还包括继承的
UIEvent
属性:¥It also includes the inherited
UIEvent
properties:
TransitionEvent
处理函数
¥TransitionEvent
handler function
CSS 转场事件的事件处理程序类型。
¥An event handler type for the CSS transition events.
<div
onTransitionEnd={e => console.log('onTransitionEnd')}
/>
参数
¥Parameters
-
e
:具有这些额外TransitionEvent
属性的 React 事件对象:¥
e
: A React event object with these extraTransitionEvent
properties:
UIEvent
处理函数
¥UIEvent
handler function
通用 UI 事件的事件处理程序类型。
¥An event handler type for generic UI events.
<div
onScroll={e => console.log('onScroll')}
/>
参数
¥Parameters
-
e
:具有这些额外UIEvent
属性的 React 事件对象:¥
e
: A React event object with these extraUIEvent
properties:
WheelEvent
处理函数
¥WheelEvent
handler function
onWheel
事件的事件处理程序类型。
¥An event handler type for the onWheel
event.
<div
onWheel={e => console.log('onWheel')}
/>
参数
¥Parameters
-
e
:具有这些额外WheelEvent
属性的 React 事件对象:¥
e
: A React event object with these extraWheelEvent
properties:它还包括继承的
MouseEvent
属性:¥It also includes the inherited
MouseEvent
properties:它还包括继承的
UIEvent
属性:¥It also includes the inherited
UIEvent
properties:
用法
¥Usage
应用 CSS 样式
¥Applying CSS styles
在 React 中,你指定一个带有 className
。 的 CSS 类,它的作用类似于 HTML 中的 class
属性:
¥In React, you specify a CSS class with className
. It works like the class
attribute in HTML:
<img className="avatar" />
然后在单独的 CSS 文件中为其编写 CSS 规则:
¥Then you write the CSS rules for it in a separate CSS file:
/* In your CSS */
.avatar {
border-radius: 50%;
}
React 没有规定你如何添加 CSS 文件。在最简单的情况下,你将向 HTML 添加 <link>
标记。如果你使用构建工具或框架,请查阅其文档以了解如何将 CSS 文件添加到你的项目中。
¥React does not prescribe how you add CSS files. In the simplest case, you’ll add a <link>
tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project.
有时,样式值取决于数据。使用 style
属性动态传递一些样式:
¥Sometimes, the style values depend on data. Use the style
attribute to pass some styles dynamically:
<img
className="avatar"
style={{
width: user.imageSize,
height: user.imageSize
}}
/>
在上面的示例中,style={{}}
不是特殊语法,而是 style={ }
JSX 大括号 中的常规 {}
对象 我们建议仅在你的样式依赖于 JavaScript 变量时使用 style
属性。
¥In the above example, style={{}}
is not a special syntax, but a regular {}
object inside the style={ }
JSX curly braces. We recommend only using the style
attribute when your styles depend on JavaScript variables.
export default function Avatar({ user }) { return ( <img src={user.imageUrl} alt={'Photo of ' + user.name} className="avatar" style={{ width: user.imageSize, height: user.imageSize }} /> ); }
深入研究
¥How to apply multiple CSS classes conditionally?
要有条件地应用 CSS 类,你需要使用 JavaScript 自己生成 className
字符串。
¥To apply CSS classes conditionally, you need to produce the className
string yourself using JavaScript.
例如,className={'row ' + (isSelected ? 'selected': '')}
将生成 className="row"
或 className="row selected"
,具体取决于 isSelected
是否为 true
。
¥For example, className={'row ' + (isSelected ? 'selected': '')}
will produce either className="row"
or className="row selected"
depending on whether isSelected
is true
.
为了使其更具可读性,你可以使用像 classnames
: 这样的小型辅助库
¥To make this more readable, you can use a tiny helper library like classnames
:
import cn from 'classnames';
function Row({ isSelected }) {
return (
<div className={cn('row', isSelected && 'selected')}>
...
</div>
);
}
如果你有多个条件类,这将特别方便:
¥It is especially convenient if you have multiple conditional classes:
import cn from 'classnames';
function Row({ isSelected, size }) {
return (
<div className={cn('row', {
selected: isSelected,
large: size === 'large',
small: size === 'small',
})}>
...
</div>
);
}
使用引用操作 DOM 节点
¥Manipulating a DOM node with a ref
有时,你需要获取与 JSX 中的标记关联的浏览器 DOM 节点。例如,如果要在单击按钮时聚焦 <input>
,则需要在浏览器 <input>
DOM 节点上调用 focus()
。
¥Sometimes, you’ll need to get the browser DOM node associated with a tag in JSX. For example, if you want to focus an <input>
when a button is clicked, you need to call focus()
on the browser <input>
DOM node.
要获取标签 声明引用 的浏览器 DOM 节点并将其作为 ref
属性传递给该标签:
¥To obtain the browser DOM node for a tag, declare a ref and pass it as the ref
attribute to that tag:
import { useRef } from 'react';
export default function Form() {
const inputRef = useRef(null);
// ...
return (
<input ref={inputRef} />
// ...
渲染到屏幕后,React 会将 DOM 节点放入 inputRef.current
。
¥React will put the DOM node into inputRef.current
after it’s been rendered to the screen.
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> </> ); }
阅读有关 使用引用操作 DOM 和 查看更多示例。 的更多信息。
¥Read more about manipulating DOM with refs and check out more examples.
对于更高级的用例,ref
属性还接受 回调函数。
¥For more advanced use cases, the ref
attribute also accepts a callback function.
危险地设置内部 HTML
¥Dangerously setting the inner HTML
你可以像这样将原始 HTML 字符串传递给元素:
¥You can pass a raw HTML string to an element like so:
const markup = { __html: '<p>some raw html</p>' };
return <div dangerouslySetInnerHTML={markup} />;
这很危险。与底层 DOM innerHTML
属性一样,你必须格外小心!除非标记来自完全可信的来源,否则以这种方式引入 XSS 漏洞是微不足道的。
¥This is dangerous. As with the underlying DOM innerHTML
property, you must exercise extreme caution! Unless the markup is coming from a completely trusted source, it is trivial to introduce an XSS vulnerability this way.
例如,如果你使用将 Markdown 转换为 HTML 的 Markdown 库,你相信它的解析器不包含错误,并且用户只能看到他们自己的输入,你可以像这样显示生成的 HTML:
¥For example, if you use a Markdown library that converts Markdown to HTML, you trust that its parser doesn’t contain bugs, and the user only sees their own input, you can display the resulting HTML like this:
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 的变量才会传递到 dangerouslySetInnerHTML
。不建议像 <div dangerouslySetInnerHTML={{__html: markup}} />
那样内联创建对象。
¥The {__html}
object should be created as close to where the HTML is generated as possible, like the above example does in the renderMarkdownToHTML
function. This ensures that all raw HTML being used in your code is explicitly marked as such, and that only variables that you expect to contain HTML are passed to dangerouslySetInnerHTML
. It is not recommended to create the object inline like <div dangerouslySetInnerHTML={{__html: markup}} />
.
要了解为什么渲染任意 HTML 是危险的,请将上面的代码替换为:
¥To see why rendering arbitrary HTML is dangerous, replace the code above with this:
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
与可信且经过清理的数据一起使用。
¥The code embedded in the HTML will run. A hacker could use this security hole to steal user information or to perform actions on their behalf. Only use dangerouslySetInnerHTML
with trusted and sanitized data.
处理鼠标事件
¥Handling mouse events
此示例显示了一些常见的 鼠标事件 以及它们何时触发。
¥This example shows some common mouse events and when they fire.
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> ); }
处理指针事件
¥Handling pointer events
此示例显示了一些常见的 指针事件 以及它们何时触发。
¥This example shows some common pointer events and when they fire.
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> ); }
处理焦点事件
¥Handling focus events
在 React 中,焦点事件 气泡。你可以使用 currentTarget
和 relatedTarget
来区分聚焦或模糊事件是否源自父元素外部。该示例展示了如何检测聚焦子元素、聚焦父元素,以及如何检测进入或离开整个子树的焦点。
¥In React, focus events bubble. You can use the currentTarget
and relatedTarget
to differentiate if the focusing or blurring events originated from outside of the parent element. The example shows how to detect focusing a child, focusing the parent element, and how to detect focus entering or leaving the whole subtree.
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> ); }
处理键盘事件
¥Handling keyboard events
此示例显示了一些常见的 键盘事件 以及它们何时触发。
¥This example shows some common keyboard events and when they fire.
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> ); }