我有一个 Next.js 应用程序,我需要一个图像,填充其容器的全高,同时自动决定其宽度基于其长宽比。
我试过以下方法:
<Image src="/deco.svg" alt="" layout="fill" />
此代码片段编译成功,但在前端,我看到以下错误:
错误: 具有 src“/dec.svg”的图像必须使用“ width”和“ height”属性或“ unsize”属性。
这使我感到困惑,因为根据 那些文件,这些属性是使用 layout="fill"时所需的 没有。
layout="fill"
我认为还应该像下面这样在 Image 元素上提供 object-fit 属性:-
<Image alt="Mountains" src="/mountains.jpg" layout="fill" objectFit="cover" />
Nextjs 提供的示例可以是 https://github.com/vercel/next.js/blob/canary/examples/image-component/pages/layout-fill.js
我就是这么做的。
与 next/image合作:
next/image
<div style=\{\{width: '100%', height: '100%', position: 'relative'}}> <Image alt='Mountains' src='/mountains.jpg' layout='fill' objectFit='contain' /> </div>
以及 next/future/image:
next/future/image
<Image fill alt='Mountains' src='/mountains.jpg' sizes='100vw'/>
下一个/未来/图像
这里有一个方法: 例如,我想有一个图像,涵盖其容器的整个宽度和高度是一个 div。
<div className={'image-container'}> <Image src={path} layout="fill" className={'image'} /> </div>
这就是风格: (有一个容器 div 占据了视窗的一半宽度和高度,我的图像将覆盖它。)
// Nested Styling .image-container { width: 50vw; height: 50vh; position: relative; .image { width: 100%; height: 100%; position: relative !important; object-fit: cover; // Optional } } // Or Normal Styling .image-container { width: 50vw; height: 50vh; position: relative; } .image-container .image { width: 100%; height: 100%; position: relative !important; object-fit: cover; // Optional }
<img src="/path/to/image.jpg" alt="" title="" />
在 NextJS 12及以下
<Image src="/path/to/image.jpg" alt="" title="" width="100%" height="100%" layout="responsive" objectFit="contain"/>
如果您不想使用高度和宽度的绝对值,也就是 px 等,您可以这样做
<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>
原始来源 Https://stackoverflow.com/a/66358533/12242764
如果有人使用带样式的组件的 NextJS,它可以工作:
const Container = styled.div` width: 100%; div, span { position: unset !important; } .image { object-fit: contain; width: 100% !important; position: relative !important; height: unset !important; } `; <Container> <Image src={ src } layout="fill" className={ "image" } /> </Container>
<img alt="" src="https://some/image/uri" loading="lazy" />
在 NextJS
<div> <Image alt="" src="https://some/image/uri" width="100%" height="100%" layout="fill" objectFit="contain" /> </div>
它在 next.js 图像组件中工作
<Image src="/path/image.jpg" alt="" title="" width="100%" height="100%" layout="responsive" objectFit="cover"/>
我没问题
<div style=\{\{ display: 'flex', flexDirection: 'column', height: 'auto', maxHeight: 343, position: 'relative' }} > <Image src={`<YOU_IMAGE>`} alt="thumbnail" width="100%" height="100%" layout="responsive" /> </div>
<Image src="/deco.svg" alt="alternative text" fill style=\{\{height: "100%", width:"100%"}} />
对我来说,在导入图像并将其从 public移开后,在 下一个13中工作得很好:
public
之前
<Image src='/link-to-public/img.png' alt="topmoto.pro" />
之后
import img from "../assets/img.png"; ... <Image src={img} alt="topmoto.pro" />