【问题标题】:Image properties in Next.jsNext.js 中的图像属性
【发布时间】:2021-03-27 13:55:24
【问题描述】:

我正在尝试在我的组件中使用 Next.js 图像组件进行自动图像优化。

import Image from "next/image";

const PicArrs = () => (
  <Image src="remote-location" alt="ViewCrunch" layout="responsive" />
)

但我收到此错误:

错误:带有 SRC“/renmote-location”的图像必须使用“width”和“height”属性或“unsized”属性。

注意: 我希望图像采用 div 的大小,这就是为什么我将其设置为 layout="responsive" 但是当我设置不需要的高度和宽度时,我不会得到这个错误。

我已经阅读了文档,并且如前所述,我什至将布局设置为填充,即使文档说如果布局设置为填充,您不需要 height/width 属性,我仍然会收到此错误。

【问题讨论】:

    标签: reactjs next.js nextjs-image


    【解决方案1】:

    当我第一次开始使用 Next 的图像组件时,我遇到了同样的问题。

    为了使图像具有响应性,我们需要为 Image 组件指定初始宽度和高度(以像素为单位)。然后,响应式布局将根据屏幕尺寸缩小或放大我们的图像。根据Next's image docs,默认断点为deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840]

    在我的例子中,我的父 div 的宽度是 680px,所以这就是我使用的宽度,如下所示。但是,即使我使用 1000px 作为宽度,Image 组件仍然会尊重父 div 的宽度。

    <Image
      src="/img/cool_cat.png"
      alt="Pretty cool cat"
      width={680}
      height={400}
      layout="responsive"
    />
    

    使用unsized 属性有效,因为我们说我们的图像没有大小。 Next 的 Image 组件中断了这个 layout="fill",它不会尊重父 div 的宽度,从而导致意想不到的后果。

    【讨论】:

      【解决方案2】:

      你能试试这个代码吗?

      const PicArrs = () => (
             <Image src="remote-location" alt="PedroView" layout="responsive" unsized />
       )
      

      【讨论】:

      • 非常感谢,我不再收到错误,但图像现在不尊重专利 div 的高度和宽度
      猜你喜欢
      • 1970-01-01
      • 2021-11-19
      • 2022-11-16
      • 2014-07-13
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      相关资源
      最近更新 更多