常用组件(例如 <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>

请参阅下面的更多示例。

¥See more examples below.

属性

¥Props

所有内置组件都支持这些特殊的 React 属性:

¥These special React props are supported for all built-in components:

  • children:一个 React 节点(一个元素、一个字符串、一个数字、一个门户, 一个空节点,如 nullundefined 和布尔值,或其他 React 节点的数组)。指定组件内部的内容。当你使用 JSX 时,你通常会通过像 <div><span /></div> 这样的嵌套标签来隐式指定 children 属性。

    ¥children: A React node (an element, a string, a number, a portal, an empty node like null, undefined and booleans, or an array of other React nodes). Specifies the content inside the component. When you use JSX, you will usually specify the children 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 the innerHTML 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 using dangerouslySetInnerHTML.

  • ref:来自 useRefcreateRef 的引用对象,或 ref 回调函数,旧版引用。 的字符串 你的引用将填充此节点的 DOM 元素。阅读更多关于使用引用操作 DOM 的内容。

    ¥ref: A ref object from useRef or createRef, or a ref 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 对同时具有 childrencontentEditable={true}(通常不能一起工作)的元素显示的警告。如果你正在构建手动管理 contentEditable 内容的文本输入库,请使用此选项。

    ¥suppressContentEditableWarning: A boolean. If true, suppresses the warning that React shows for elements that both have children and contentEditable={true} (which normally do not work together). Use this if you’re building a text input library that manages the contentEditable 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 set suppressHydrationWarning to true, 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 }。与 DOM style 属性类似,CSS 属性名称需要写成 camelCase,例如 fontWeight 而不是 font-weight。你可以将字符串或数字作为值传递。如果你传递一个数字,比如 width: 100,React 会自动将 px (“pixels”) 附加到该值,除非它是 无单位的属性。。我们建议仅将 style 用于你事先不知道样式值的动态样式。在其他情况下,使用 className 应用纯 CSS 类会更有效。阅读有关 classNamestyle 的更多信息。

    ¥style: An object with CSS styles, for example { fontWeight: 'bold', margin: 20 }. Similarly to the DOM style property, the CSS property names need to be written as camelCase, for example fontWeight instead of font-weight. You can pass strings or numbers as values. If you pass a number, like width: 100, React will automatically append px (“pixels”) to the value unless it’s a unitless property. We recommend using style only for dynamic styles where you don’t know the style values ahead of time. In other cases, applying plain CSS classes with className is more efficient. Read more about className and style.

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

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

你还可以将自定义属性作为属性传递,例如 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

    ¥You cannot pass both children and dangerouslySetInnerHTML at the same time.

  • 有些事件(比如 onAbortonLoad)不会在浏览器中冒泡,但会在 React 中冒泡。

    ¥Some events (like onAbort and onLoad) 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)} />

请参阅使用 ref 回调的示例。

¥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 or null. React will pass you the DOM node when the ref gets attached, and null when the ref gets detached. Unless you pass the same function reference for the ref callback on every render, the callback will get temporarily detached and re-attached during every re-render of the component.

Canary

返回

¥Returns

  • 可选 cleanup function:当 ref 分离时,React 将调用清理函数。如果 ref 回调未返回函数,则当 ref 分离时,React 会以 null 作为参数再次调用回调。

    ¥optional cleanup function: When the ref is detached, React will call the cleanup function. If a function is not returned by the ref callback, React will call the callback again with null as the argument when the ref gets detached.


<div ref={(node) => {
console.log(node);

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

注意事项

¥Caveats

  • 当严格模式打开时,React 将在第一次真正设置之前运行一个额外的仅开发设置+清理周期。这是一个压力测试,可确保你的清理逻辑 “mirrors” 你的设置逻辑,并确保它停止或撤消设置正在执行的任何操作。如果这导致问题,请实现清理功能。

    ¥When Strict Mode is on, React will run one extra development-only setup+cleanup cycle before the first real setup. This is a stress-test that ensures that your cleanup logic “mirrors” your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, implement the cleanup function.

  • 当你传递不同的 ref 回调时,React 将调用前一个回调的清理函数(如果提供)。如果未定义清理函数,则将以 null 作为参数调用 ref 回调。下一个函数将使用 DOM 节点调用。

    ¥When you pass a different ref callback, React will call the previous callback’s cleanup function if provided. If not cleanup function is defined, the ref callback will be called with null as the argument. The next function will be called with the DOM node.


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 whether preventDefault 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:

  • nativeEvent:A DOM Event.原始浏览器事件对象。

    ¥nativeEvent: A DOM Event. The original browser event object.

方法

¥Methods

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

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

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

¥Additionally, React event objects provide these methods:

  • isDefaultPrevented():返回一个布尔值,指示是否调用了 preventDefault

    ¥isDefaultPrevented(): Returns a boolean value indicating whether preventDefault was called.

  • isPropagationStopped():返回一个布尔值,指示是否调用了 stopPropagation

    ¥isPropagationStopped(): Returns a boolean value indicating whether stopPropagation 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 whether persist has been called.

注意事项

¥Caveats

  • currentTargeteventPhasetargettype 的值反映了你的 React 代码期望的值。在幕后,React 在根部附加了事件处理程序,但这并没有反映在 React 事件对象中。例如,e.currentTarget 可能与基础 e.nativeEvent.currentTarget 不同。对于 polyfilled 事件,e.type(React 事件类型)可能不同于 e.nativeEvent.type(底层类型)。

    ¥The values of currentTarget, eventPhase, target, and type 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 underlying e.nativeEvent.currentTarget. For polyfilled events, e.type (React event type) may differ from e.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


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


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')}
/>

看一个例子。

¥See an example.

参数

¥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')}
/>

看一个例子。

¥See an example.

参数

¥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')}
/>

看一个例子。

¥See an example.

参数

¥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')}
/>

看一个例子。

¥See an example.

参数

¥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': '')} 将生成 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 中,焦点事件 气泡。你可以使用 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>
  );
}


React 中文网 - 粤ICP备13048890号