You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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"],
  },
};

截图

图片路径已识别但无法加载
图片元素渲染但无内容

解决方案

以下是几个优先级从高到低的修复方向:

  1. 替换domains为remotePatterns
    Next.js 13推荐使用更安全的remotePatterns配置图片域名,替换原domains配置:
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "cdn.sanity.io",
      },
      {
        protocol: "https",
        hostname: "images.pexels.com",
      },
    ],
  },
};
  1. 为Image组件添加object-fit样式
    使用fill属性时,需明确图片适配方式,避免默认样式导致图片不可见:
<Image 
  src={props.src} 
  alt={props.alt} 
  fill 
  style={{ objectFit: "cover" }} // 可根据需求替换为contain
/>
  1. 验证Sanity图片URL完整性
    确保Sanity返回的图片URL包含尺寸参数(如?w=1000&h=600),Next.js Image组件需要明确尺寸信息做优化。若URL缺少尺寸,可通过Sanity图片转换API添加,或为Image组件指定原始width和height属性(即使使用fill,指定原始尺寸也能帮助组件优化渲染)。

  2. 检查父元素样式有效性
    通过浏览器开发者工具确认figure元素的padding-top计算值正常,若出现NaN或异常值,会导致图片无显示空间,可添加边界处理:

padding-top: ${props.width > 0 ? ((props.height / props.width) * 100).toFixed(2) : 0}%;

内容的提问来源于stack exchange,提问作者happycoder2121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:16:30