nextjs - 将图像作为与 next/image 一起使用的道具传递

aki*_*kio 5 javascript reactjs next.js

我的index.js如下

import Head from 'next/head'
import Layout, { siteTitle } from '../components/layout'
import Homecard from '../components/homecard'
import logo from '../public/images/logo.jpg'

export default function Home() {
  return (
    <Layout>
      <Head>
        <title>{siteTitle}</title>
      </Head>
      <div className='d-flex'>
        <Homecard img={logo} />
      </div>

    </Layout>
  )
}
Run Code Online (Sandbox Code Playgroud)

这是我的 Homecard 组件

import styles from '../styles/homecard.module.css'
import Image from 'next/image'

export default function Homecard({ img }) {

    return (
        <div style={{width: '33.33%'}}>
            <Image src={img} />
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误

Error: Image with src "/images/logo.jpg" must use "width" and "height" properties or "layout='fill'" property.
Run Code Online (Sandbox Code Playgroud)

如果我添加填充布局图像不响应,如果我不添加图像不显示。如果我像这样更改我的 Homecard 组件,它就会起作用。

Error: Image with src "/images/logo.jpg" must use "width" and "height" properties or "layout='fill'" property.
Run Code Online (Sandbox Code Playgroud)

包.json

import styles from '../styles/homecard.module.css'
import Image from 'next/image'
import logo from '../public/images/logo.jpg'

export default function Homecard({ img }) {

    return (
        <div style={{width: '33.33%'}}>
            <Image src={logo} />
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

如何将图像作为组件道具传递而不会出现该错误?

编辑

我像这样改变了我的标记

{
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^6.1.1",
    "@fortawesome/free-solid-svg-icons": "^6.1.1",
    "@fortawesome/react-fontawesome": "^0.1.18",
    "date-fns": "^2.28.0",
    "gray-matter": "^4.0.3",
    "next": "latest",
    "normalize.css": "^8.0.1",
    "prop-types": "^15.8.1",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "remark": "^14.0.2",
    "remark-html": "^15.0.1"
  }
}

Run Code Online (Sandbox Code Playgroud)

错误消失,但没有响应,图像扭曲

aki*_*kio 0

经过一段时间的搜索后,我发现 nextjs github 页面上的讨论似乎我不是唯一遇到这个问题的人

{/* https://github.com/vercel/next.js/discussions/18739#discussioncomment-344932 */}
<div className={styles.imageContainer}>
    <Image src={logo} layout='fill' className={styles.image}/>                    
</div>
Run Code Online (Sandbox Code Playgroud)
.imageContainer {
    width: 100%;
}

.imageContainer>span { /* OR change span to div */
    position: unset !important;
}

.image {
    object-fit: contain;
    width: 100% !important;
    position: relative !important;
    height: unset !important;
}
Run Code Online (Sandbox Code Playgroud)