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

Next.js中div内使用img标签报错问题求助

解决Next.js中div内使用原生img标签报错的问题

报错原因

在Next.js 13+的App Router模式下,框架默认强制要求使用官方<Image>组件替代原生<img>标签,以此保障图片的性能优化与可访问性合规,直接使用原生<img>会触发报错。

解决方案

方案1:替换为Next.js官方Image组件(推荐)

将代码中的原生<img>标签替换为next/image组件,同时注意以下细节:

  • 先从next/image导入组件
  • 必须指定width和height属性(或使用fill配合父容器定位)
  • 本地图片需放置在项目根目录的public文件夹下

修改后的代码示例:

import Image from 'next/image';

<div
  id="default-sidebar"
  className="flex fixed flex-col w-64 h-screen px-3 py-3 bg-base font-sans overflow-y-auto mx-ato my-0 "
>
  <div className="relative inline-block">
    <Image
      src="/xpertcoin-logo-new-dark.png"
      alt="logo"
      className="w-full h-auto"
      width={240} // 根据实际图片尺寸设置,也可使用fill属性适配父容器
      height={60}
    />
  </div>

  <div className="flex flex-col justify-between flex-1 mt-12">
    <nav className="space-y-3">
      <Link
        className="rounded-md flex items-center px-3 py-2 bg-themeColor hover:bg-themecolor-100"
        href="#"
      >
        <Image
          width={16}
          height={16}
          className="align-middle"
          preview={false}
          src="/exchange.png"
          alt="icon"
        />
        <span className="ml-3 font-normal text-white text-sm">Exchanges</span>
      </Link>
    </nav>
  </div>
</div>

另外,代码中存在class与className混用的情况,React/Next.js中需统一使用className设置样式,避免潜在渲染问题。

方案2:允许使用原生img标签(不推荐)

若特殊场景下需保留原生<img>,可在next.config.js中添加配置开启兼容:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    allowDeprecatedImgTag: true,
  },
};

module.exports = nextConfig;

此方式会失去Next.js图片组件的优化能力,仅作为临时兼容方案使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:20:29