NextJS 具有固定宽度和自动高度的图像组件

Jka*_*ram 41 reactjs next.js tailwind-css nextjs-image

我正在使用 NextJS 图像组件。我希望图像填充 100% 宽度并采用保持纵横比所需的高度。我已经尝试了此代码的许多不同变体,但除非我在父 div 上定义固定高度,否则它将无法工作。

export default function PhotoCard({ img }: Props) {
      return (
        <div className="relative w-full h-32 my-2">
          <Image alt={img.title} src={img.url} layout="fill" objectFit="cover" />
        </div>
      );
    }
Run Code Online (Sandbox Code Playgroud)

这是当前的行为 应用程序中的图像

jul*_*ves 91

从 Next.js 13 开始,该next/image组件允许直接使用style/设置底层图像的样式className。这意味着您可以直接在组件上应用width: 100%和。height: autoImage

import Image from 'next/image';

<Image
    src={img1}
    width="0"
    height="0"
    sizes="100vw"
    style={{ width: '100%', height: 'auto' }}
/>
Run Code Online (Sandbox Code Playgroud)

或者,如果使用 Tailwind CSS。

import Image from 'next/image';

<Image
    src={img1}
    width="0"
    height="0"
    sizes="100vw"
    className="w-full h-auto"
/>
Run Code Online (Sandbox Code Playgroud)

在 Next.js 13 之前,上述功能只能通过 实现next/future/image,从 12.2 版本开始,仍处于实验阶段,可以在 标志下next/future/image启用。next.config.jsexperimental

module.exports = {
    experimental: {
        images: {
            allowFutureImage: true
        }
    },
    // Other configs
}
Run Code Online (Sandbox Code Playgroud)


Abh*_*hek 6

对于那些遇到如下错误的人:

 Image with src "image path" has either width or height modified, but not the other. If you use CSS to change the size of your image, also include the styles 'width: "auto"' or 'height: "auto"' to maintain the aspect ratio.
Run Code Online (Sandbox Code Playgroud)

将宽度和高度属性设置为 0 并添加具有所需高度或宽度的样式,并将宽度或高度设置为自动将解决此问题

             <Image
                src="image path"
                height={0}
                width={0}
                style={{width:'120px', height: "auto" }}
              />
Run Code Online (Sandbox Code Playgroud)


rav*_*218 5

正如 Next.js 在其文档中提到的,为了避免布局移位,需要 width 和 height 属性,使用 layout="fill" 将仅填充先前设置的容器高度和宽度。这基本上意味着为了保持宽高比,您必须提前知道图像的高度和宽度。

不过幸运的是,Next.js 还通过一个名为 的事件为我们提供了解决此问题的方法onLoadingComplete,该事件为我们提供了一个包含图像自然高度和宽度的事件参数。

<Image
   layout="fill"
   src="/cat.jpg"
   onLoadingComplete={e => console.log(e)} // {naturalHeight: ..., naturalWidth: ...}
/>
Run Code Online (Sandbox Code Playgroud)

您可以使用很多选项来使用此信息来保持图像的纵横比,例如useState设置元素的高度和宽度或使图像响应,具体取决于您的需要。无论如何,希望这对您有所帮助。

  • @莫。未来的图像组件看起来很有前途。 (2认同)

小智 -1

您可以尝试用“%”方式设置宽度和高度。

<Image src={image.url} alt={image.title} width="100%" height="100%" layout="responsive" objectFit="contain"/>
Run Code Online (Sandbox Code Playgroud)

或者您可以使用“vw”属性设置宽度,如下所示。

<Image src={image.url} alt={image.title} width="100vw" height="100%" layout="responsive" objectFit="contain"/>
Run Code Online (Sandbox Code Playgroud)