内置浏览器 <img> 组件(链接)让你可以嵌入图片。

🌐 The built-in browser <img> component lets you embed an image.

<img src="photo.jpg" alt="A person walking through a park" />

参考

🌐 Reference

<img>

要显示图片,请渲染内置浏览器 <img> 组件。

🌐 To display an image, render the built-in browser <img> component.

<img src="photo.jpg" alt="A person walking through a park" />

查看更多示例。

属性

🌐 Props

<img> 支持所有常用元素属性。

  • alt:一个字符串。指定图片的替代文本。对于纯装饰性的图片,请使用空字符串。
  • crossOrigin:一个字符串。指定在获取图片时要使用的 CORS 策略。可能的值是 anonymous 和 use-credentials。
  • decoding:一个字符串。表示浏览器是否应该在显示其他内容之前等待解码图片。可能的值是 async、sync 和 auto(默认)。
  • fetchPriority:一个字符串。表示获取图片的相对优先级。可能的值有 high、low 和 auto(默认值)。在服务器渲染期间,fetchPriority="low" 还可以防止 React 自动预加载图片。
  • height:一个数字或字符串。指定图片渲染的高度。
  • loading:一个字符串。指定浏览器是否应该延迟加载图片,直到它接近视口。可能的值是 eager(默认)和 lazy。设置 loading="lazy" 可以防止 React 自动预加载图片。
  • onError:一个 事件处理器 函数。当图片加载失败时触发。
  • onLoad:一个 事件处理器 函数。当图片加载完成时触发。传入 onLoad 可以防止 React 在客户端渲染的视图过渡更新时 等待图片加载。
  • referrerPolicy:一个字符串。指定在获取图片时要发送的引用者信息。
  • sizes:一个字符串。指定不同页面布局的图片尺寸。用于 srcSet。
  • src:一个字符串。指定图片的 URL。
  • srcSet:一个字符串。指定一个或多个候选图片来源供浏览器选择。
  • useMap:一个字符串。将图片与客户端图片映射关联。
  • width:一个数字或字符串。指定图片的渲染宽度。

注意事项

🌐 Caveats

  • 不要向 src 传递空字符串。这可能会导致浏览器再次请求当前页面。React 在开发环境下会发出警告并忽略该属性。如果不想显示图片,可以省略 <img> 或向 src 传递 null。
  • <img> 不能有子元素,也不能使用 dangerouslySetInnerHTML。如果你传入其中任何一个,React 会报错。
  • fetchPriority="low" 不会阻止 React 在客户端渲染的视图过渡更新中等待图片加载。使用 loading="lazy" 或 onLoad 处理器可以选择不采用这种行为。

用法

🌐 Usage

显示图片

🌐 Displaying an image

把图片网址传给 src,把文字描述传给 alt:

🌐 Pass the image URL to src and a text description to alt:

export default function Profile() {
  return (
    <img
      src="https://react.nodejs.cn/images/docs/scientists/yXOvdOSs.jpg"
      alt="Hedy Lamarr"
      width={100}
      height={100}
    />
  );
}

当你知道图片的尺寸时,指定 width 和 height,这样浏览器在图片加载前就能预留空间。如果是装饰性图片,传入 alt="",让屏幕阅读器忽略它。

🌐 Specify width and height when you know the image dimensions so the browser can reserve space before the image loads. For a decorative image, pass alt="" so that screen readers ignore it.


在服务器渲染时控制图片预加载

🌐 Controlling image preloading during server rendering

在服务器渲染期间,React 默认会自动为 <img> 生成预加载提示。这可以让浏览器在遇到渲染后的 HTML 中的 <img> 之前就开始获取图片。

🌐 During server rendering, React automatically generates a preload hint for an <img> by default. This can let the browser start fetching the image before it encounters the <img> in the rendered HTML.

在不应该收到这个提示的图片上添加 loading="lazy" 或 fetchPriority="low":

🌐 Add loading="lazy" or fetchPriority="low" to an image that should not receive this hint:

function ProductPage() {
return (
<>
<img src="hero.jpg" alt="Featured product" />
<img src="thumbnail.jpg" alt="Related product" loading="lazy" />
<img src="secondary.jpg" alt="Another product" fetchPriority="low" />
</>
);
}

在这个例子中,React 只为 hero.jpg 生成了预加载提示。根据服务器的 API 或框架,React 可能会渲染这个元素的等效内容:

🌐 In this example, React generates a preload hint only for hero.jpg. Depending on the server API or framework, React may render the equivalent of this element:

<link rel="preload" as="image" href="hero.jpg" />

React 可能会在 Link 响应头中提供相同的提示。其他两个图片在渲染的 HTML 中保留了它们的 loading 和 fetchPriority 属性,但 React 不会为它们生成预加载提示。loading="lazy" 属性会让浏览器延迟加载图片,直到它接近视口。fetchPriority="low" 属性允许图片立即加载,但会告诉浏览器以较低的优先级去获取它。

🌐 React may instead provide the same hint in a Link response header. The other two images keep their loading and fetchPriority props in the rendered HTML, but React does not generate preload hints for them. The loading="lazy" prop asks the browser to defer loading an image until it approaches the viewport. The fetchPriority="low" prop allows the image to load immediately, but tells the browser to fetch it at a lower priority.

当图片在 <picture> 或 <noscript> 元素里面,或者它的 src 或 srcSet 是数据 URL 时,React 也不会自动预加载图片。

🌐 React also does not automatically preload an image when it is inside a <picture> or <noscript> element, or when its src or srcSet is a data URL.

如果你通过框架或组件库渲染图片,查阅它的文档以了解默认行为。React 会根据底层 <img> 的属性决定是否生成自动预加载。例如,一个图片组件可能默认添加 loading="lazy",并提供一个单独的选项,用于显式地预加载选定的图片。

🌐 If you render an image through a framework or a component library, consult its documentation for the default behavior. React decides whether to generate an automatic preload from the props of the underlying <img>. For example, an image component may add loading="lazy" by default and provide a separate option for explicitly preloading selected images.

要创建一个显式的预加载提示,调用 preload。

🌐 To create an explicit preload hint, call preload.


在视图切换时等待图片

🌐 Waiting for an image during a View Transition

在 <ViewTransition> 更新期间,React 会等待最多 500 毫秒让可见图片加载完毕,然后才开始动画。这包括新渲染的 <img> 元素以及 src 或 srcSet 发生变化的现有图片。设置 loading="lazy" 或添加 onLoad 处理程序可以让图片跳过等待。

🌐 During a <ViewTransition> update, React waits up to 500 ms for visible images to load before starting the animation. This includes newly rendered <img> elements and existing images whose src or srcSet changes. Setting loading="lazy" or adding an onLoad handler opts an image out.

比较同一张图片在 Suspense 边界内部和外部显示其内容时的样子,使用 <ViewTransition>:

🌐 Compare how the same image appears when a Suspense boundary reveals its content inside and outside a <ViewTransition>:

import {
  ViewTransition,
  Suspense,
  use,
  useState,
} from 'react';
import { fetchImageSrc } from './image.js';

function Profile({ cacheKey }) {
  const src = use(fetchImageSrc(cacheKey));
  return (
    <div className="card">
      <img src={src} alt="" width={80} height={80} />
      <p>Jack Pope</p>
    </div>
  );
}

function ProfilePlaceholder() {
  return (
    <div className="card">
      <div className="avatar-placeholder" />
      <p className="name-placeholder">&nbsp;</p>
    </div>
  );
}

export default function App() {
  const [showWithTransition, setShowWithTransition] =
    useState(false);
  const [showWithoutTransition, setShowWithoutTransition] =
    useState(false);
  return (
    <>
      <button onClick={() => setShowWithTransition(true)}>
        Show profile with View Transition
      </button>
      {showWithTransition && (
        <ViewTransition>
          <Suspense fallback={<ProfilePlaceholder />}>
            <Profile cacheKey="with-transition" />
          </Suspense>
        </ViewTransition>
      )}
      <hr />
      <button onClick={() => setShowWithoutTransition(true)}>
        Show profile without View Transition
      </button>
      {showWithoutTransition && (
        <Suspense fallback={<ProfilePlaceholder />}>
          <Profile cacheKey="without-transition" />
        </Suspense>
      )}
    </>
  );
}

使用 <ViewTransition> 时,React 会在图片加载时保持骨架界面可见最长 500 毫秒,这样卡片可以在图片已经加载好的情况下显示出来。没有 <ViewTransition> 时,Suspense 一旦 Promise 解决就会停止显示骨架界面。如果图片还在加载,卡片会先出现,图片随后才会显示出来。

🌐 With <ViewTransition>, React keeps the skeleton visible for up to 500 ms while the image loads, so the card can be revealed with its image already in place. Without <ViewTransition>, Suspense stops showing the skeleton as soon as the Promise resolves. If the image is still loading, the card appears first and the image pops in afterward.