常用组件(例如 <div>)

所有内置浏览器组件,例如 <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 节点(一个元素、一个字符串、一个数字、一个门户, 一个空节点比如 nullundefined 和布尔值,或者一个由其他 React 节点组成的数组)。指定组件内部的内容。当你使用 JSX 时,通常通过嵌套标签如 <div><span /></div> 隐式指定 children 属性。
  • dangerouslySetInnerHTML:一个形式为 { __html: '<p>some html</p>' } 的对象,内部包含原始 HTML 字符串。它会覆盖 DOM 节点的 innerHTML 属性,并显示传入的 HTML 内容。使用时应格外小心!如果内部的 HTML 不可信(例如基于用户数据),你可能会引入 XSS 漏洞。了解更多关于使用 dangerouslySetInnerHTML 的信息。
  • ref:来自 useRefcreateRef 的 ref 对象,或 ref 回调函数, 或用于旧版 refs 的字符串。你的 ref 将被填充为该节点的 DOM 元素。了解更多关于使用 refs 操作 DOM 的信息。
  • suppressContentEditableWarning:一个布尔值。如果为 true,会抑制 React 对同时具有 childrencontentEditable={true} 的元素显示的警告(它们通常不能一起使用)。如果你正在构建一个手动管理 contentEditable 内容的文本输入库,请使用此选项。
  • suppressHydrationWarning:一个布尔值。如果你使用服务器渲染,通常当服务器和客户端渲染的内容不同时会有警告。在某些罕见情况下(例如时间戳),很难或不可能保证完全匹配。如果你将 suppressHydrationWarning 设置为 true,React 不会对该元素的属性和内容不匹配发出警告。它只在一级深度有效,旨在作为应急手段使用。不要过度使用它。阅读有关抑制水合错误的内容
  • style:一个具有 CSS 样式的对象,例如 { fontWeight: 'bold', margin: 20 }。类似于 DOM style 属性,CSS 属性名称需要写成 camelCase,例如 fontWeight 而不是 font-weight。你可以传递字符串或数字作为值。如果你传递一个数字,比如 width: 100,React 会自动在值后面加上 px(“像素”),除非它是一个 无单位属性。我们建议仅在你事先不知道样式值的动态样式中使用 style。在其他情况下,使用 className 应用普通 CSS 类更有效。阅读有关 classNamestyle 的更多内容。

所有内置组件也支持这些标准 DOM 属性:

🌐 These standard DOM props are also supported for all built-in components:

你也可以将自定义属性作为 props 传递,例如 mycustomprop="someValue"。这在与第三方库集成时可能很有用。自定义属性名必须是小写字母,并且不能以 on 开头。其值将被转换为字符串。如果你传递 nullundefined,该自定义属性将被移除。

🌐 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:

这些事件仅在 <dialog> 元素上触发。与浏览器事件不同,它们在 React 中会冒泡:

🌐 These events fire only for the <dialog> elements. Unlike browser events, they bubble in React:

这些事件仅在 <details> 元素上触发。与浏览器事件不同,它们在 React 中会冒泡:

🌐 These events fire only for the <details> elements. Unlike browser events, they bubble in React:

这些事件会在 <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:

这些事件会在像 <audio><video> 这样的资源上触发。与浏览器事件不同,它们会在 React 中冒泡:

🌐 These events fire for resources like <audio> and <video>. Unlike browser events, they bubble in React:

注意事项

🌐 Caveats

  • 你不能同时传入 childrendangerouslySetInnerHTML
  • 有些事件(比如 onAbortonLoad)在浏览器中不会冒泡,但在 React 中会冒泡。

ref 回调函数

🌐 ref callback function

你可以将一个函数传递给 ref 属性,而不是传递一个 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('Attached', node);

return () => {
console.log('Clean up', node)
}
}}>

查看使用 ref 回调的示例。

<div> DOM 节点被添加到屏幕上时,React 会使用 DOM node 作为参数调用你的 ref 回调。当该 <div> DOM 节点被移除时,React 会调用从回调中返回的清理函数。

🌐 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 the cleanup function returned from the callback.

每当你传入一个不同的 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 节点。当 ref 被附加时,React 会将 DOM 节点传递给你。除非你在每次渲染时都传递相同的函数引用给 ref 回调,否则该回调会在组件每次重新渲染时暂时清理并重新创建。

注意

React 19 为 ref 回调添加了清理函数。

🌐 React 19 added cleanup functions for ref callbacks.

为了支持向后兼容,如果 ref 回调没有返回清理函数,当 ref 被分离时,node 将使用 null 被调用。此行为将在未来的版本中被移除。

🌐 To support backwards compatibility, if a cleanup function is not returned from the ref callback, node will be called with null when the ref is detached. This behavior will be removed in a future version.

返回

🌐 Returns

  • 可选 cleanup function:当 ref 被分离时,React 会调用清理函数。如果 ref 回调没有返回函数,当 ref 被分离时,React 会再次以 null 作为参数调用该回调。此行为将在将来的版本中移除。

注意事项

🌐 Caveats

  • 当严格模式开启时,React 会在第一次真正的 setup 之前额外运行一次仅用于开发的 setup+cleanup 循环。这是一个压力测试,用于确保你的 cleanup 逻辑与 setup 逻辑“镜像”,并停止或撤销 setup 所做的任何操作。如果这导致问题,请实现 cleanup 函数。
  • 当你传递一个不同的 ref 回调时,如果提供了,React 将调用上一个回调的清理函数。如果没有定义清理函数,ref 回调将以 null 作为参数被调用。下一个函数将以 DOM 节点为参数被调用。

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 中冒泡。
  • [cancelable](https://web.nodejs.cn/en-US/docs/Web/API/Event/cancelable):布尔值。返回事件是否可以取消。
  • currentTarget:一个 DOM 节点。返回当前处理程序在 React 树中附加的节点。
  • defaultPrevented:一个布尔值。返回 preventDefault 是否被调用。
  • eventPhase:一个数字。返回事件当前处于哪个阶段。
  • isTrusted:一个布尔值。返回事件是否由用户发起。
  • target:一个 DOM 节点。返回事件发生的节点(可能是一个远程子节点)。
  • timeStamp:一个数字。返回事件发生的时间。

此外,React 事件对象提供以下属性:

🌐 Additionally, React event objects provide these properties:

  • nativeEvent:一个 DOM Event。原始的浏览器事件对象。

方法

🌐 Methods

React 事件对象实现了一些标准 Event 方法:

🌐 React event objects implement some of the standard Event methods:

此外,React 事件对象提供了这些方法:

🌐 Additionally, React event objects provide these methods:

  • isDefaultPrevented():返回一个布尔值,指示是否调用了 preventDefault
  • isPropagationStopped():返回一个布尔值,指示是否调用了 stopPropagation
  • persist():不用于 React DOM。在 React Native 中,在事件之后调用此方法以读取事件的属性。
  • isPersistent():不适用于 React DOM。在 React Native 中,返回 persist 是否已被调用。

注意事项

🌐 Caveats

  • currentTargeteventPhasetargettype 的值反映了你的 React 代码所期望的值。在底层,React 会在根节点附加事件处理程序,但这并不会反映在 React 事件对象中。例如,e.currentTarget 可能与底层的 e.nativeEvent.currentTarget 不同。对于带有 polyfill 的事件,e.type(React 事件类型)可能与 e.nativeEvent.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


ClipboardEvent 处理函数

🌐 ClipboardEvent handler function

用于 Clipboard 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


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


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


FocusEvent 处理函数

🌐 FocusEvent handler function

焦点事件的事件处理程序类型。

🌐 An event handler type for the focus events.

<input
onFocus={e => console.log('onFocus')}
onBlur={e => console.log('onBlur')}
/>

查看示例。

参数

🌐 Parameters


Event 处理函数

🌐 Event handler function

通用事件的事件处理程序类型。

🌐 An event handler type for generic events.

参数

🌐 Parameters


InputEvent 处理函数

🌐 InputEvent handler function

onBeforeInput 事件的事件处理程序类型。

🌐 An event handler type for the onBeforeInput event.

<input onBeforeInput={e => console.log('onBeforeInput')} />

参数

🌐 Parameters


KeyboardEvent 处理函数

🌐 KeyboardEvent handler function

键盘事件的事件处理程序类型。

🌐 An event handler type for keyboard events.

<input
onKeyDown={e => console.log('onKeyDown')}
onKeyUp={e => console.log('onKeyUp')}
/>

查看示例。

参数

🌐 Parameters


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


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


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


TransitionEvent 处理函数

🌐 TransitionEvent handler function

CSS 转场事件的事件处理程序类型。

🌐 An event handler type for the CSS transition events.

<div
onTransitionEnd={e => console.log('onTransitionEnd')}
/>

参数

🌐 Parameters


UIEvent 处理函数

🌐 UIEvent handler function

通用 UI 事件的事件处理程序类型。

🌐 An event handler type for generic UI events.

<div
onScroll={e => console.log('onScroll')}
/>

参数

🌐 Parameters


WheelEvent 处理函数

🌐 WheelEvent handler function

onWheel 事件的事件处理程序类型。

🌐 An event handler type for the onWheel event.

<div
onWheel={e => console.log('onWheel')}
/>

参数

🌐 Parameters


用法

🌐 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
      }}
    />
  );
}

深入研究

如何有条件地应用多个 CSS 类?

🌐 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': '')} 将根据 isSelected 是否为 true 生成 className="row"className="row selected"

🌐 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 并将其作为 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>
    </>
  );
}

阅读更多关于使用 refs 操作 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 漏洞是非常容易的。

例如,如果你使用将 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,并且只有你期望包含 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 中,聚焦事件 会冒泡。你可以使用 currentTargetrelatedTarget 来区分聚焦或失焦事件是否源自父元素之外。示例展示了如何检测子元素被聚焦、父元素被聚焦,以及如何检测焦点进入或离开整个子树。

🌐 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>
  );
}