如何在Next.js Image中使用Tailwind CSS

61

我正在尝试在 Next.js 项目中使用 Tailwind CSS,但我无法在 Next.js Image 组件中使用我的 Tailwind 类。

这是我的代码:

<Image
    src={img.img}
    alt="Picture of the author"
    width="200"
    height="200"
    className="bg-mint text-mint fill-current"
></Image>
我想使用 Tailwind 类替代 Next.js 图像的 heightwidth 属性,但由于出现错误而无法实现。此外,unsized 属性会抛出另一个错误,指出它已被弃用。有什么解决方法吗?
如果不使用 heightwidth 属性,就会出现以下错误。 enter image description here 当我使用 layout='fill' 属性时,只显示一张图片。 如果我使用 unsized 属性,则会显示以下错误。 enter image description here

请与我们分享错误输出。 - Juan Marco
@JuanMarco 更新了... - Pranta
4个回答

100

在Next.js的GitHub项目中,有一个讨论和相关示例。听起来这个示例可以实现你想要做的事情。简而言之:

<div className="h-64 w-96 relative"> // "relative" is required; adjust sizes to your liking
  <Image
    src={img.img}
    alt="Picture of the author"
    layout="fill" // required
    objectFit="cover" // change to suit your needs
    className="rounded-full" // just an example
  />
</div>

该图像将保留其原始纵横比,并填充/覆盖(或任何您选择的object-fit)外部div的大小,您可以使用Tailwind类进行设置。其他样式,例如圆角,可以应用于Image


2
有没有一种方法可以根据内容确定高度,而不是图像的高度? - thiras
@thiras 我最后使用了 aspect-[] 来解决这个问题。 - undefined

5

3
当我阅读Next.js 13文档时,我发现了一个非常重要的事情,那就是在使用Next.js的Image标签时,父容器应该是相对定位的。
fill

fill={true} // {true} | {false}

一个布尔值,使图像填充父元素而不是设置宽度和高度。
父元素必须分配position: "relative"、position: "fixed"或position: "absolute"样式。
默认情况下,img元素将自动分配position: "absolute"样式。
默认的图像适应行为会拉伸图像以适应容器。您可能更喜欢为镶嵌在容器中并保持纵横比的图像设置object-fit: "contain"。
或者,object-fit: "cover"将导致图像填充整个容器,并被裁剪以保持纵横比。为了看起来正确,应该将overflow: "hidden"样式分配给父元素。
有关更多信息,请参见:
position
object-fit
object-position

所以我就这样做了:
<div className="relative w-full h-full overflow-hidden">
  <Image   
                                                        
      className="rounded-sm"  
      object-fit="cover" 
      fill={true}  
      alt={group?.name ? group.name : "no details" }
      src="https://www.oddcircles.com/images/group-image.png" 
  />
</div>

-1
你可以使用一个 div 容器并给它应用一个类。
<div className="bg-mint text-mint fill-current">
    <Image
        src={img.img}
        alt="Picture of the author"
        width="200"
        height="200">
    </Image>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接