【发布时间】:2021-06-21 09:14:22
【问题描述】:
我使用的是最新版本的 NextJS 10.0.9。我有一张我正在尝试显示的图片,但是我收到了错误:
Error: Image with src "https://picsum.photos/480/270" must use "width" and "height" properties or "layout='fill'" property.
正如您在此处看到的,我确实设置了所有这些属性:
<div className="card-img">
<Image
alt={media?.title}
title={media?.title}
src={media?.previewImage || 'https://picsum.photos/480/270'}
width={480}
height={270}
layout="fill"
/>
</div>
出于某种原因,使用默认外部图像似乎不想与 Image 组件很好地配合使用。有谁知道解决方法或可能出现这种情况的原因?
还有一点附注:我在layout 属性上有一个 Typescript 错误,上面写着“Type '"fill"' is not assignable to type '"fixed" | "intrinsic" | "responsive" | undefined ’。”。不知道有没有关系?
【问题讨论】:
-
请务必注意,如果您使用填充布局,则无需指定宽度或高度。我使用您在此处提供的图像创建了一个沙箱:codesandbox.io/s/goofy-swirles-5h1si?file=/pages/index.js。确保将域添加到 next.config.js,尽管我假设您可能已经拥有该域,否则您会看到该错误。
-
谢谢亚历克斯!我知道我已经接近了,只是无法完全正确。我最终保留了
layout="fill",并将高度/宽度应用于父 div。使这项工作发挥作用的另一件事是我注意到您使用了objectFit="cover"属性。再次感谢! -
没问题,是的,我只是补充说,以确保它在保持纵横比的同时填充父母空间,您可能不希望在您的用例中使用它
标签: next.js nextjs-image