bub*_*ser 7 image next.js nextjs-image
从版本 10 开始,Next.js 带有内置Image组件,该组件提供图像优化和响应式调整图像大小的功能。我非常喜欢它,并且一直在我的网站上使用它来处理固定大小的图像。根据官方文档, width 和 height 是必需的道具,除非是 for layout=fill.
现在,Image即使我不知道宽度和高度,我也想使用组件。我有来自 CMS 的博客资源,其中图像的确切大小未知。在这种情况下,有什么办法可以使用Image组件吗?
任何帮助,将不胜感激。
Pau*_*ard 16
我也遇到了同样的问题:我想在MUI的砌体中Image使用next/imageImageList ...
无论如何,这是我用来获取图像大小并处理容器大小的技巧:
import React, { FC, useState } from 'react';
import styled from 'styled-components';
import Image from 'next/image';
interface Props {
src: string;
}
export const MasonryItem: FC<Props> = ({ src }) => {
const [paddingTop, setPaddingTop] = useState('0');
return (
<Container style={{ paddingTop }}>
<Image
src={src}
layout="fill"
objectFit="contain"
onLoad={({ target }) => {
const { naturalWidth, naturalHeight } = target as HTMLImageElement;
setPaddingTop(`calc(100% / (${naturalWidth} / ${naturalHeight})`);
}}
/>
</Container>
);
};
const Container = styled.div`
position: relative;
`;
Run Code Online (Sandbox Code Playgroud)
想法:加载图像时获取图像的大小,计算比率并使用它使容器用 padding-top 填充所需的空间。这样,无论您的图像大小如何,容器都将适合它。
备注,我没有在容器上使用宽度或高度,因为我的项目不需要它,但也许您必须为您的项目设置两者之一。
由于我仍在从 React & NextJS & typescript 开始,也许解决方案可以更漂亮,如果有人有改进它的想法,我会很高兴阅读它!
小智 6
是的,您可以将它与layout=fill您提到的选项一起使用。
在这种情况下,您需要为图像设置“纵横比”
<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>
Run Code Online (Sandbox Code Playgroud)
您也可以使用objectFit="cover"它,它会放大您的图像以填充所有容器。
这种方法的缺点是将附加到width您指定的内容上,它可以是相对的,例如“100%”或绝对值,例如“10rem”,但无法根据大小设置自动宽度和高度你的形象,或者至少还没有。