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

Next.js使用API图片报错:原生img正常但Image组件失效

Next.js Image组件替换原生img后报错的解决方案

问题

用原生<img>能正常加载API返回的图片,但换成Next.js的Image组件就报错。错误提示为:Error: Invalid src prop (xxx) on 'next/image', hostname "xxx" is not configured under images in your next.config.js

你的代码

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import Image from 'next/image';

const ChannelDetailCard = ({
  data,
  id,
  channel_image,
  channel_name,
}) => {
  return (
    <>
      <div className="ml-0 flex justify-center lg:flex lg:ml-10">
        <Image
          className="w-64 h-64 object-cover rounded"
          src={channel_image}
          objectFit="contain"
          layout='fill'
        />
      </div>  
    </> 
  ) 
}

原因分析

  1. 域名未授权:Next.js的Image组件出于安全和性能考虑,默认只允许加载指定域名的图片,你的API图片域名不在允许列表里。
  2. 布局属性冲突:使用layout='fill'时,父容器必须设置position: relative,否则组件无法正确定位;同时fill模式下通过className设置宽高会和组件自身布局逻辑冲突。

解决步骤

1. 配置图片域名白名单

在项目根目录的next.config.js中添加你的图片域名:

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https', // 改成你图片的实际协议,http或https
        hostname: 'your-image-domain.com', // 替换成实际的图片域名
        pathname: '/**', // 允许该域名下所有路径的图片
      },
    ],
  },
};

module.exports = nextConfig;

配置完成后重启开发服务器生效。

2. 修正布局配置

如果继续使用layout='fill',给父容器加上相对定位,并调整组件的className:

<div className="ml-0 flex justify-center lg:flex lg:ml-10 relative w-64 h-64">
  <Image
    className="object-cover rounded"
    src={channel_image}
    objectFit="cover"
    layout='fill'
    alt={channel_name} // 建议添加alt属性,提升可访问性
  />
</div>

3. 替代方案:直接指定宽高

如果不需要填充父容器,去掉layout='fill',直接设置width和height:

<Image
  className="object-cover rounded"
  src={channel_image}
  width={256} // w-64对应256px
  height={256} // h-64对应256px
  objectFit="cover"
  alt={channel_name}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:36:18