如何在 Next.js 中仅指定图像高度并保持宽高比?

Kaz*_*Ute 5 image reactjs next.js nextjs-image

我只想指定图像高度并保持图像纵横比而不对宽度进行硬编码。

在传统img元素中我可以这样做:

<img src="/logo.png" alt="logo" height={30} />
Run Code Online (Sandbox Code Playgroud)

但如果我尝试使用next/image

<Image src="/logo.png" alt="logo" height={30} />;
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

错误:带有 src“/logo.png”的图像必须使用“width”和“height”属性或“layout='fill'”属性。

jul*_*ves 4

您可以设置layout="fill"和 ,objectFit="contain"使其Image在填充容器时保持其纵横比。div然后,您可以在组件周围添加一个包装器Image并将其应用height到它。

<div style={{ position: 'relative', height: '30px' }}>
    <Image
        src="/logo.png"
        layout="fill"
        objectFit="contain"
    />
</div>
Run Code Online (Sandbox Code Playgroud)