【问题标题】:nextjs Image property nullnextjs 图片属性 null
【发布时间】:2022-02-08 21:29:50
【问题描述】:

我有一个包含动态内容的组件,如下所示: <Image width="680" height="400" src={post.imgsrc} alt={post.title} />

即使我添加了宽度/高度,我仍然遇到同样的错误:

src 为“/imgs/paintings/2022/2.jpg”的图像必须使用“width”和“height”属性或“layout='fill'”属性。

我不知道为什么,我想知道为什么我必须指定宽度和高度,因为我的图片有不同的尺寸......

【问题讨论】:

  • 您需要提供数值:<Image width={680} height={400} ...。而要求他们的原因是为了防止cumulative layout shift。
  • 非常感谢,不知道这个!

标签: next.js


【解决方案1】:

要提一提的是,如果图像是本地图像,您可以导入它们,如果您希望不需要使用宽度、高度或填充。 它们会自动提供

来自docs的示例:

import profilePic from '../public/me.png'

import Image from 'next/image'
import profilePic from '../public/me.png'

function Home() {
  return (
    <>
      <h1>My Homepage</h1>
      <Image
        src={profilePic}
        alt="Picture of the author"
        // width={500} automatically provided
        // height={500} automatically provided
        // blurDataURL="data:..." automatically provided
        // placeholder="blur" // Optional blur-up while loading
      />
      <p>Welcome to my homepage!</p>
    </>
  )
}

This 还解释了为什么远程图像确实需要这些属性。

【讨论】:

  • 非常感谢,我现在知道了,我用了导入的方法,它可以工作了。
猜你喜欢
  • 2021-05-03
  • 2022-06-19
  • 2022-11-20
  • 2021-04-11
  • 2021-09-18
  • 2017-03-11
  • 2015-08-31
  • 2017-04-13
  • 2013-03-28
相关资源
最近更新 更多