将Gatsby-plugin-Image的Gatsby图像与数组一起使用时出现问题 [英] Problem using GatsbyImage of gatsby-plugin-image with array
本文介绍了将Gatsby-plugin-Image的Gatsby图像与数组一起使用时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的函数中,我有一个包含id、标题和图像的数组:
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', image: 'https://placekitten.com/800/600' },
]
使用<img>
标记,我只能查看来自Web的最后两个占位符图像。但我想使用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', image: 'https://placekitten.com/800/600' },
]
或者,如果您希望使用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]
)
}
}
}
}
`
资源:
- https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-plugin-image/#gatsbyimage
- https://www.gatsbyjs.com/plugins/gatsby-plugin-image/
这篇关于将Gatsby-plugin-Image的Gatsby图像与数组一起使用时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文