【问题标题】:How can I use next.js 13 image without providing width and height?如何在不提供宽度和高度的情况下使用 next.js 13 图像?
【发布时间】:2022-11-22 10:40:52
【问题描述】:

Next.js 13 已发布。重构的组件之一是next/image

我想使用它,但我想使用 tailwind 设置图像大小。

这是我的代码:

import Image from 'next/image'

const Index = () => {
   return (
       <div>
           <Image
               src="https://picsum.photos/800/600"
               layout="fill"
               className="w-48 aspect-square md:w-72 xl:w-48"
           />
       </div>
   )
}

我得到这个错误:

错误:带有 src“https://picsum.photos/800/600”的图像缺少必需的“宽度”属性。

然而,在docs中,据说可以在不指定widthheight的情况下使用fill

我在这里想念什么?

【问题讨论】:

  • 如果我没记错的话,新图像组件会收到一个 fill 属性,它是一个布尔值,而不是 layout 属性。试试&lt;Image fill ... /&gt;。我相信这个“​​新”组件在 Next.js 12.2+ 上被称为 next/future/image,您可以查看 this answer,可能会有帮助。
  • @ivanatias,是的,做到了。谢谢你。您可以发表您的评论作为答案,以便我接受吗?

标签: next.js


【解决方案1】:

Next.js v13 新图像组件接收一个 fill 属性,它是一个布尔值而不是旧的 layout 属性。例子:

<Image
  src="https://picsum.photos/800/600"
  fill
  ...
/>

此外,您现在可以使用 styleclassName 为组件的底层图像元素设置样式。

使用 Tailwind CSS 的示例:

<Image
  src="some-image-url"
  width="0"
  height="0"
  sizes="100vw"
  className="w-full h-auto"
/>

【讨论】:

    【解决方案2】:

    没有宽度和高度

            <Image 
                  layout="fill"
                  objectFit="cover"
                  className="addClassName"
                  src={src} alt="" 
                />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-16
      • 2014-09-13
      • 2016-10-09
      • 1970-01-01
      • 2021-08-15
      • 2021-05-26
      • 2012-06-25
      • 2017-07-30
      相关资源
      最近更新 更多