NextJS开发:Image组件的使用及缺陷
Next.js 中的 Image 组件相比于传统的 img 标签有以下几个优点:
懒加载:Image 组件自带懒加载,当页面滚动到 Image 组件所在位置时才会加载图片,从而加快页面的渲染速度。
自动优化:Image 组件会自动将图片压缩、转换格式、调整大小,以达到更好的性能和用户体验。
支持多种图片源:Image 组件支持使用本地文件、远程 URL、云存储等多种方式来加载图片,更加灵活方便。
支持响应式图片:Image 组件可以根据不同设备屏幕大小来加载不同分辨率的图片,以达到最佳的视觉效果和性能表现。此外,Image 组件还可以使用 layout 属性来控制图片的布局方式,包括填充、响应式、不变形等多种方式。
总之,Next.js 中的 Image 组件在性能、用户体验、开发效率等方面都优于传统的 img 标签,因此在开发过程中应当优先考虑使用 Image 组件。
<Image src={props.data.thumb}
width={800} height={600} alt={""}
className=" w-full overflow-hidden rounded-md cursor-pointer mb-3"
/>
NextJS中的Image,加载其他域名地址下图片会出现如下错误:
⨯ Error: Invalid src prop (https://images.xxx.com/photo/2023/dd2434067ce2093f77ef0a2b22725913.png) on `next/image`, hostname "images.xxx.com" is not configured under images in your `next.config.js`
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host
at Array.map (<anonymous>)
解决方法:
next.config.js文件中加入
const nextConfig = {
reactStrictMode: true,
images: {
domains: ['images.xxx.com']
}
}
如果你项目中有不确定的任意域名图片的需求,还是用img标签吧,没有找到nextConfig中通配符允许任意域名的配置方式。
使用img标签,npm run build可能会报如下警告
./src/app/(components)/article-row.tsx
18:11 Warning: Using `<img>` could result in slower LCP and higher bandwidth. Consider using `<Image />` from `next/image` to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-img-element @next/next/no-img-element
18:11 Warning: img elements must have an alt prop, either with meaningful text, or an empty string for decorative images. jsx-a11y/alt-text
改为
<picture>
<img src={props.data.thumb}/>
</picture>
警告不再出现