Next.js 13新next/image组件搭配Sanity.io图片无法加载求助
Next.js 13 next/image 无法加载Sanity图片的排查与解决
问题描述
使用Next.js 13版本的新next/image组件渲染Sanity.io存储的图片时,图片始终无法显示。已确认src、alt属性传递正确,资源路径可被识别,但图片仍不加载。
相关代码
/app/Figure.tsx
"use client"; import Image from "next/image"; interface Props { src: string; alt: string; width: number; height: number; } export default function Figure(props: Props) { return ( <figure> <style jsx>{` figure { position: relative; width: 100%; margin: 0; padding-top: ${((props.height / props.width) * 100).toFixed(2)}%; } `}</style> <Image src={props.src} alt={props.alt} fill /> </figure> ); }
next.config.js
module.exports = { images: { domains: ["cdn.sanity.io", "images.pexels.com"], }, };
截图


解决方案
以下是几个优先级从高到低的修复方向:
- 替换
domains为remotePatterns
Next.js 13推荐使用更安全的remotePatterns配置图片域名,替换原domains配置:
module.exports = { images: { remotePatterns: [ { protocol: "https", hostname: "cdn.sanity.io", }, { protocol: "https", hostname: "images.pexels.com", }, ], }, };
- 为Image组件添加
object-fit样式
使用fill属性时,需明确图片适配方式,避免默认样式导致图片不可见:
<Image src={props.src} alt={props.alt} fill style={{ objectFit: "cover" }} // 可根据需求替换为contain />
验证Sanity图片URL完整性
确保Sanity返回的图片URL包含尺寸参数(如?w=1000&h=600),Next.js Image组件需要明确尺寸信息做优化。若URL缺少尺寸,可通过Sanity图片转换API添加,或为Image组件指定原始width和height属性(即使使用fill,指定原始尺寸也能帮助组件优化渲染)。检查父元素样式有效性
通过浏览器开发者工具确认figure元素的padding-top计算值正常,若出现NaN或异常值,会导致图片无显示空间,可添加边界处理:
padding-top: ${props.width > 0 ? ((props.height / props.width) * 100).toFixed(2) : 0}%;
内容的提问来源于stack exchange,提问作者happycoder2121
相关产品推荐
相关产品推荐

