如何在 Next.js 中使用未知宽度和高度的图像组件 [英] How to use Image component in Next.js with unknown width and height

查看:117
本文介绍了如何在 Next.js 中使用未知宽度和高度的图像组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从版本 10 开始,Next.js 带有内置的 Image 组件,该组件提供图像优化和响应式调整图像大小的功能.我非常喜欢它,并且我一直在我的网站上使用它来获取固定大小的图像.根据官方文档,除非是 layout=fill,否则 width 和 height 是必需的属性.

Since version 10, Next.js comes with the built-in Image component which provides the feature of image optimization and resizing image responsively. I like it a lot and I've been using it across my website for images with fixed size. According to the official documentation, width and height are required props unless it's for layout=fill.

现在,即使我事先不知道宽度和高度,我也想使用 Image 组件.我有来自 CMS 的博客资源,其中图像的确切大小未知.在这种情况下,有什么方法可以使用 Image 组件吗?

Now, I would like to use Image component even when I don't know width and height ahead of time. I have blog resources that come from a CMS where the exact size of image is unknown. In this case, is there any way I could use Image component?

任何帮助将不胜感激.

推荐答案

是的,您可以将它与您提到的 layout=fill 选项一起使用.

Yeah, you could use it with the layout=fill option you mentioned.

在这种情况下,您需要设置纵横比".为您的图像

On this case, you're gonna need to set an "aspect ratio" for your images

<div style={{ position: "relative", width: "100%", paddingBottom: "20%" }} >
  <Image
    alt="Image Alt"
    src="/image.jpg"
    layout="fill"
    objectFit="contain" // Scale your image down to fit into the container
  />
</div>

您也可以使用 objectFit="cover",它会放大图像以填满所有容器.

You can use objectFit="cover" too and it'll scale your image up to fill all the container.

这种方法的缺点是会附加到您指定的 width 上,它可能是相对的,例如100%";或绝对的,例如10rem",但无法根据图像大小设置自动宽度和高度,或者至少现在还没有.

The downside of this approach is that is gonna be attached to the width you specify, it could be relative such as "100%" or absolute e.g. "10rem", but there's no way to set like an auto width and height based on the size of your image, or at least no yet.

这篇关于如何在 Next.js 中使用未知宽度和高度的图像组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆