微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用带有数组的 gatsby-plugin-image 的 GatsbyImage 的问题

如何解决使用带有数组的 gatsby-plugin-image 的 GatsbyImage 的问题

在我的函数中,我有一个包含 id、title 和 image 的数组:

const arrays = [
    { id: 1,title: 'First Title',image: 'images/photo1.jpg' },{ id: 2,title: 'Second Title',image: 'images/photo2.jpg' },{ id: 3,title: 'Third Title',image: 'https://placekitten.com/800/600' },{ id: 4,title: 'Fourth Title',]

使用 <img> 标记,我只能查看来自网络的最后两个占位符图像。但我想使用 gatsby-plugin-image。我已阅读文档并需要使用 GatsbyImage 标记,但是当我使用它时看不到图像。

        <ul className="text-center wrap">
            {arrays.map((array,image) => (
              <li key={project.id}>
                <a
                  className="mx-auto text-3xl lg:text-4xl wrap-txt transition-all duration-300 z-40"
                  onMouseEnter={() => setIsShown(array.id)}
                  onMouseLeave={() => setIsShown(0)}
                  href="/"
                >
                  {array.title}
                </a>
                {isShown === array.id && (
                  <div className="w-1/4 absolute bottom-10 ">
                    <GatsbyImage image={array.image} className="w-full z-40" alt="" />
                  </div>
                )}
              </li>
            ))}
          </ul>

有人知道我该如何继续吗?

解决方法

您不能使用未解析和未转换图像的 GatsbyImage 组件。 Gatsby 需要使用其解析器和转换器来处理您想要显示的图像。此过程将创建一个 GraphQL 节点,其中包含 Gatsby 文件系统中设置的所有图像所需的数据,因此,您需要在项目中本地存储数据,或者,您可能希望使用 StaticImage,它接受​​远程图像,但不接受动态数据(例如您的对象数组)。

在获取 CMS 数据时,插件负责处理此过程并允许您将外部图像与 GatsbyImage 组件一起使用。

在你的情况下,我会调试为什么你只看到最后两张使用 img 标签的图像,这似乎与路径的相对性有关。也许这对你有用:

const arrays = [
    { id: 1,title: 'First Title',image: '../images/photo1.jpg' },{ id: 2,title: 'Second Title',image: '../images/photo2.jpg' },{ id: 3,title: 'Third Title',image: 'https://placekitten.com/800/600' },{ id: 4,title: 'Fourth Title',]

或者,如果您想使用 GatsbyImage,则需要在本地下载和存储图像,并相应地设置 gatsby-plugin-filesystem。假设您将图像下载并本地存储在 /src/images 中:

{
  resolve: `gatsby-source-filesystem`,options: {
    name: `images`,path: `${__dirname}/src/images/`,},

Gatsby 会知道您的图像存储在哪里,并会创建适当的 GraphQL 解析器,从而允许您使用 childImageSharp。您可以在 localhost:8000/___graphql 查看它们的可用性。例如:

import { graphql } from "gatsby"
import { GatsbyImage,getImage } from "gatsby-plugin-image"

function BlogPost({ data }) {
 const image = getImage(data.blogPost.avatar)
 return (
   <section>
     <h2>{data.blogPost.title}</h2>
     <GatsbyImage image={image} alt={data.blogPost.author} />
     <p>{data.blogPost.body}</p>
   </section>
 )
}

export const pageQuery = graphql`
 query {
   blogPost(id: { eq: $Id }) {
     title
     body
     author
     avatar {
       childImageSharp {
         gatsbyImageData(
           width: 200
           placeholder: BLURRED
           formats: [AUTO,WEBP,AVIF]
         )
       }
     }
   }
 }
`

资源:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。