Jak*_*ake 12 javascript reactjs next.js nextjs-image
我有一个 Next.js 应用程序,我需要一个图像来填充其容器的整个高度,同时根据其纵横比自动确定其宽度。
我尝试了以下方法:
<Image
src="/deco.svg"
alt=""
layout="fill"
/>
Run Code Online (Sandbox Code Playgroud)
此代码段编译成功,但在前端,我看到以下错误:
错误:带有 src "/deco.svg" 的图像必须使用 "width" 和 "height" 属性或 "unsized" 属性。
这让我困惑,因为根据该文档,在这些属性不使用的时候需要layout="fill"。
Nis*_*hah 153
2023 年,上述所有解决方案均已弃用,
使用下面
<Image
src="url"
width={0}
height={0}
sizes="100vw"
style={{ width: '100%', height: 'auto' }} // optional
/>
Run Code Online (Sandbox Code Playgroud)
Github:https://github.com/vercel/next.js/discussions/18474#discussioncomment-5501724
Muh*_*BUL 34
<img src="/path/to/image.jpg" alt="" title="" />
Run Code Online (Sandbox Code Playgroud)
在 NextJS 12 及更低版本中
<Image src="/path/to/image.jpg" alt="" title="" width="100%" height="100%" layout="responsive" objectFit="contain"/>
Run Code Online (Sandbox Code Playgroud)
Pey*_*eri 24
这是一种方法:例如,我想要一个覆盖其容器(div)的整个宽度和高度的图像。
<div className={'image-container'}>
<Image src={path} layout="fill" className={'image'} />
</div>
Run Code Online (Sandbox Code Playgroud)
这是样式:(有一个容器 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
}
Run Code Online (Sandbox Code Playgroud)
Beh*_*zad 14
在接下来的 v13 中
\n <Image\n src={src}\n width={200}\n height={160}\n alt={alt}\n sizes="(max-width: 768px) 100vw,\n (max-width: 1200px) 50vw,\n 33vw"\n style={{ height: '100%', width: '100%' }} //The point is right there!\n //OR className='w-100 h-100'\n />\nRun Code Online (Sandbox Code Playgroud)\n感谢 @Ab\xc3\xadlio Soares Coelho
\n小智 11
我认为还可以在 Image 元素上提供 object-fit 属性,如下所示:-
<Image
alt="Mountains"
src="/mountains.jpg"
layout="fill"
objectFit="cover"
/>
Run Code Online (Sandbox Code Playgroud)
Nextjs 提供的示例可以是https://github.com/vercel/next.js/blob/canary/examples/image-component/pages/layout-fill.js
fra*_*cis 11
这对我有用:
<div style='width:104px;height:104px;position:relative;'>
<Image
alt='Mountains'
src='/mountains.jpg'
layout='fill'
objectFit='contain'
/>
</div>
Run Code Online (Sandbox Code Playgroud)
小智 5
<Image
src="/deco.svg"
alt="alternative text"
fill
style={{height: "100%", width:"100%"}}
/>
Run Code Online (Sandbox Code Playgroud)
也许这些其他答案适用于不同的 NextJS 版本,但它们都不适合我。
我正在使用 NextJS v13.0.0
为了实现这一点,我有以下 JSX(使用 TailwindCSS,应该很容易转换为普通 CSS):
<div className="h-screen relative">
<Image
src="/image.png"
alt="pic of dog"
fill={true}
/>
</div>
Run Code Online (Sandbox Code Playgroud)
这里重要的部分是制作父 div position: relative(并将其高度/宽度设置为您想要的图像)并设置fill={true}. 我从 NextJS Image 文档中得到了这个:
一般图像文档: https: //nextjs.org/docs/api-reference/next/image
有关属性的文档fill:https ://nextjs.org/docs/api-reference/next/image#fill
希望这对某人有帮助!