Image
Next.js 的 Image 组件扩展了 HTML <img> 元素,实现了自动图片优化。
app/page.js
import Image from 'next/image'
export default function Page() {
return (
<Image
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
/>
)
}
提示: 如果你使用的是 Next.js 13 之前的版本,请参考 next/legacy/image 文档,因为组件名称有变更。
参考
Props
可用的 props 如下:
| Prop | 示例 | 类型 | 状态 |
|---|---|---|---|
src | src="/profile.png" | String | 必填 |
alt | alt="Picture of the author" | String | 必填 |
width | width={500} | Integer (px) | - |
height | height={500} | Integer (px) | - |
fill | fill={true} | Boolean | - |
loader | loader={imageLoader} | Function | - |
sizes | sizes="(max-width: 768px) 100vw, 33vw" | String | - |
quality | quality={80} | Integer (1-100) | - |
priority | priority={true} | Boolean | - |
placeholder | placeholder="blur" | String | - |
style | style={{objectFit: "contain"}} | Object | - |
onLoadingComplete | onLoadingComplete={img => done())} | Function | 已弃用 |
onLoad | onLoad={event => done())} | Function | - |
onError | onError(event => fail()} | Function | - |
loading | loading="lazy" | String | - |
blurDataURL | blurDataURL="data:image/jpeg..." | String | - |
overrideSrc | overrideSrc="/seo.png" | String | - |
src
图片的来源。可以是以下之一:
内部路径字符串:
<Image src="/profile.png" />
绝对外部 URL(需在 remotePatterns 中配置):
<Image src="https://example.com/profile.png" />
静态导入:
import profile from './profile.png'
export default function Page() {
return <Image src={profile} />
}
alt
alt 属性用于为屏幕阅读器和搜索引擎描述图片。当图片被禁用或加载出错时,也会显示为回退文本 。
应包含可以替代图片且不改变页面含义的文本。不应重复图片上下的说明文字。
如果图片是纯装饰性或不面向用户,alt 应设为空字符串(alt="")。
了解更多 图片可访问性指南。
width 和 height
width 和 height 属性表示图片的固有尺寸(像素)。用于让浏览器预留正确的宽高比,避免加载时布局偏移。它不决定图片的实际渲染尺寸,实际渲染由 CSS 控制。
<Image src="/profile.png" width={500} height={500} />
必须同时设置 width 和 height,除非:
- 图片是静态导入的;
- 图片使用了
fill属性
如果未知宽高,推荐使用 fill 属性。