【问题标题】:SVG is being passed to img src as an objectSVG 正在作为对象传递给 img src
【发布时间】:2022-01-23 19:02:28
【问题描述】:

对于使用 NextJS 和 Sanity.io 的网站,

我正在本地导入图像

import large_logo from '../../assets/logo-large-1200x630.svg

并在 img 标签中将其称为 src

<img src={large_logo}/>

但是,图像已损坏,无法显示。

HTML 呈现为

<img src="[object Object]">

解决这个问题的唯一方法是调用“对象”的src

<img src={large_logo.src}/>

不过香草 React does not require us to call the src.

使用 NextJS 和 Sanity 时导入不起作用吗?

【问题讨论】:

标签: reactjs next.js sanity


【解决方案1】:

对于Next.js,你必须这样做:

/* import Image component */
import Image from 'next/image';
/* import the required svg file */
import large_logo from '../../assets/logo-large-1200x630.svg

然后在JSX

<Image src={large_logo} />

【讨论】:

    【解决方案2】:

    当您使用Next.js 并且想要渲染大小超过40*40(像素)的图像时,需要从next/image 导入&lt;Image /&gt; 组件。 该组件优化您的图像并在您的应用程序中呈现。所以请按照下面的示例来帮助自己..

    import Image from 'next/image';
    import large_logo from '../../public/logo-large-1200x630.svg
    

    在您的组件中,您可以为您的图片添加此代码片段

    <Image src={large_logo} alt="logo" width={200} height={100} quality={100} />
    

    首先您需要更改图片的图片目录并将其放在您的应用程序的公共目录中,因为这是Next.js对图片需要的默认行为。

    在您的组件内部,您需要传递src 值、alt 值,通常是height - width 属性或layout 属性。

    您还可以需要Next.js的官方文档:https://nextjs.org/docs/api-reference/next/image

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多