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

Next.js Image组件width/height属性无效报错求助

问题排查与解决方案

报错原因

Next.js Image组件的width和height属性要求传入纯数值类型(不带单位),你当前通过${spacing(64)}传入的是带px单位的字符串(例如"64px"),不符合组件参数规范,因此触发无效属性的运行时错误。

解决方法

方法1:直接传入纯数值

由于你的spacing配置中64对应64px,直接将数值64传给width和height即可:

<Image
  src="/images/search_icon_green.svg"
  alt="search"
  width={64}
  height={64}
  style={{ marginTop: '-14px' }}
/>

方法2:复用全局配置(调整配置结构)

如果需要复用全局的spacing规则,可新增纯数值版本的配置,避免传递带单位的字符串:

// 修改全局样式定义,新增纯数值的spacing配置
spacingValues: {
  64: 64,
  68: 68,
}

组件中调用:

<Image
  src="/images/search_icon_green.svg"
  alt="search"
  width={spacingValues[64]}
  height={spacingValues[64]}
  style={{ marginTop: '-14px' }}
/>

方法3:通过父容器控制尺寸(配合fill属性)

若想通过带单位的样式控制尺寸,可使用Next.js Image的fill属性(Next.js 13+),同时给父容器设置定位和尺寸:

<div style={{ 
  width: spacing[64], 
  height: spacing[64], 
  position: 'relative' 
}}>
  <Image
    src="/images/search_icon_green.svg"
    alt="search"
    fill
    style={{ marginTop: '-14px', objectFit: 'contain' }}
  />
</div>

注意:父容器必须设置position: relative,否则fill属性会导致图片脱离正常布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:01:06