使用 GraphQL 映射 Gatsby 画廊图像
Posted
技术标签:
【中文标题】使用 GraphQL 映射 Gatsby 画廊图像【英文标题】:Mapping Gatsby gallery images with GraphQL 【发布时间】:2021-03-18 13:32:20 【问题描述】:我试图弄清楚如何使用 graphql 查询将画廊图像映射到 Gatsby 中的灯箱组件。我想我需要设置images = to the childimage sharp array
,但我不确定如何构造它,不断收到undefined
错误。任何指针将不胜感激。如果需要更多信息,请告诉我。
import React from "react"
import graphql, Link from "gatsby"
import Image from "gatsby-image"
import ImageGallery from 'react-image-gallery';
const ComponentName = ( data ) =>
const id, galleryImage = data.home
console.log('data is', data)
const images = [];
return (
<Layout>
<section className="template">
<ImageGallery items=images />;
</section>
</Layout>
)
export const query = graphql`
query GetSingleHome($slug: String)
home: strapiHomes(slug: eq: $slug )
galleryImage
formats
large
childImageSharp
fluid
...GatsbyImageSharpFluid
id
small
childImageSharp
fluid
...GatsbyImageSharpFluid
id
MainImage
childImageSharp
fluid
...GatsbyImageSharpFluid
`
export default ComponentName
This 是图库组件,以防万一
【问题讨论】:
【参考方案1】:根据文档,images
prop
应该是一个图像数组,因此应用于您的用例,images
必须是一个对象图像数组。
假设您的查询按预期工作并检索到正确的数据,您需要挂载一个有效的对象数组以作为图像传递prop
。
import React from "react"
import graphql, Link from "gatsby"
import Image from "gatsby-image"
import ImageGallery from 'react-image-gallery';
const ComponentName = ( data ) =>
const id, galleryImage = data.home
console.log('data is', data)
const images = [];
galleryImage.forEach(image=>
let yourImageObject=;
yourImageObject.original=image.formats.large.childImageSharp.fluid;
images.push(yourImageObject);
);
return (
<Layout>
<section className="template">
<ImageGallery items=images />;
</section>
</Layout>
)
export const query = graphql`
query GetSingleHome($slug: String)
home: strapiHomes(slug: eq: $slug )
galleryImage
formats
large
childImageSharp
fluid
...GatsbyImageSharpFluid
id
small
childImageSharp
fluid
...GatsbyImageSharpFluid
id
MainImage
childImageSharp
fluid
...GatsbyImageSharpFluid
`
export default ComponentName
您可以简化代码,但我将其拆分以使其更具可读性和可理解性。您需要遍历每个图像并为 ImageGallery
组件创建必需数据:内部具有 original
属性和内部 ...GatsbyImageSharpFluid
片段的对象数组。
如果此包不适用于 Gatsby 图像,您可能需要稍作更改以及 GraphQL 查询和代码以适应它。
我不知道该依赖项的需求,但如果需要,您也可以使用相同的方法添加 thumbnail
属性,添加:
yourImageObject.thumbnail=image.formats.small.childImageSharp.fluid;
【讨论】:
以上是关于使用 GraphQL 映射 Gatsby 画廊图像的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 reactjs 和 graphql 在 gatsby 中映射嵌套数组
如何使用 Graphql 从 Strapi 查询 Gatsby 中的多个图像
在 Gatsby 中使用 GraphQL 获取许多图像时如何保持 DRY