下一个图像不采用类属性

问题描述 投票:0回答:5

我正在使用 Next.js 和

next/image
来显示图像,但 CSS 在其中不起作用。该图像是 SVG 格式,我已将其放在公共文件夹中。我正在使用 Tailwind CSS 以及这个。

<Image
  className="mt-3"
  data-testid="close-icon"
  src="/CloseIcon.svg"
  alt="Close Nav Bar"
  height="24"
  width="24"
/>

我不确定为什么它不起作用并且没有反映在浏览器中。任何帮助将不胜感激!

reactjs next.js tailwind-css nextjs-image
5个回答
40
投票

Next.js 12.2 之前

以这种方式设置

next/image
组件边距的样式在较旧的 Next.js 版本中不起作用。有关更多详细信息,请参阅相关的 GitHub 讨论

next/image
组件内部,
<img>
元素及其包装元素具有内联样式,这些样式会覆盖通过
className
传递的某些值。

作为解决方法,您可以添加一个包装元素并对其应用

margin
样式。

<div className="mt-3">
    <Image
        data-testid="close-icon"
        src="/CloseIcon.svg"
        alt="Close Nav Bar"
        height="24"
        width="24"
    />
</div>

来自 Next.js 12.2

您可以使用

next/future/image
组件代替。这个新组件默认渲染单个
<img>
元素,无需任何额外的包装器,并且不再受包装器样式覆盖的限制。

您可以在

next/future/image
中启用
next.config.js

module.exports = {
    experimental: {
        images: {
            allowFutureImage: true
        }
    }
}

来自 Next.js 13

next/future/image
组件已转换为
next/image
。与
next/future/image
一样,此组件呈现单个
<img>
元素,并且可以直接使用
className
/
styles
设置样式。


12
投票

Juliomalves 的答案是正确的,但我更喜欢:

<div className="mt-3" height="24" width="24">
    <Image
        data-testid="close-icon"
        src="/CloseIcon.svg"
        alt="Close Nav Bar"
        layout="fill"
    />
</div>

你也可以使用一点作弊:

import {motion} from "framer-motion";

    <motion.img 
      className="mt-3"
      data-testid="close-icon"
      src="/CloseIcon.svg"
      alt="Close Nav Bar"
      height="24"
      width="24">

5
投票

试试这个:

<div style='width:104px;height:104px;position:relative;'>
  <Image
    alt='Mountains'
    src='/mountains.jpg'
    layout='fill'
    objectFit='contain'
  />
</div>

更多信息

objectFit
这里


0
投票

如果寻找快速简单的选项,而不使用类,那么您可以内联样式。当然,这存在可扩展性类型的问题,但如果它是一次性任务,那么这应该可行:

   <div style={{ marginTop: '3px' }}><Image
    data-testid="close-icon"
    src="/CloseIcon.svg"
    alt="Close Nav Bar"
    height="24"
    width="24"
/></div>

-1
投票

将图像组件包装在

div
中有助于解决我的问题。我可以将类名称应用于
div
,一切都会按预期进行。

© www.soinside.com 2019 - 2024. All rights reserved.