面试题答案
一键面试实现步骤
- 安装依赖:Next.js 内置了对图片懒加载的支持,无需额外安装第三方库。
- 使用
<Image>
组件:将原生的<img>
标签替换为 Next.js 的<Image>
组件。<Image>
组件默认开启懒加载,当图片进入视口时才会加载。
关键代码
假设项目结构如下,在 pages/index.js
页面展示图片:
import Image from 'next/image'
export default function Home() {
return (
<div>
<h1>图片展示页</h1>
<Image
src="/example.jpg"
alt="示例图片"
width={500}
height={300}
/>
<Image
src="/another-example.jpg"
alt="另一张示例图片"
width={400}
height={250}
/>
</div>
)
}
在上述代码中,src
为图片路径,alt
是图片的替代文本,width
和 height
用于设置图片的尺寸。这些尺寸是必需的,以避免布局偏移。通过使用 <Image>
组件,Next.js 会自动为图片添加懒加载功能,提升用户体验。