小编典典

如何使用gatsby-image查询多个图像?

reactjs

我有16张要以网格格式渲染到网站上的图像。

我为此使用了以下插件:

  • gatsby-image
  • gatsby-source-filesystem
  • gatsby-plugin-sharp
  • gatsby-transformer-sharp

我阅读了文档,据我所知,它仅演示了如何查询单个图像。

例如

import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"

export default ({ data }) => (
  <div>
    <h1>Hello gatsby-image</h1>
    <Img fixed={data.file.childImageSharp.fixed} />
  </div>
)

export const query = graphql`
  query {
    file(relativePath: { eq: "blog/avatars/kyle-mathews.jpeg" }) {
      childImageSharp {
        # Specify the image processing specifications right in the query.
        # Makes it trivial to update as your page's design changes.
        fixed(width: 125, height: 125) {
          ...GatsbyImageSharpFixed
        }
      }
    }
  }
`

但是,如果我有16张图像,我将如何处理?编写16个独立的查询似乎很麻烦,将来很难阅读。

我在文档中看到了引用多个图像的代码,但是尝试访问图像本身遇到了麻烦。

例如

export const squareImage = graphql`
  fragment squareImage on File {
    childImageSharp {
      fluid(maxWidth: 200, maxHeight: 200) {
        ...GatsbyImageSharpFluid
      }
    }
  }
`

export const query = graphql`
  query {
    image1: file(relativePath: { eq: "images/image1.jpg" }) {
      ...squareImage
    }

    image2: file(relativePath: { eq: "images/image2.jpg" }) {
      ...squareImage
    }

    image3: file(relativePath: { eq: "images/image3.jpg" }) {
      ...squareImage
    }
  }
`

我的文件夹结构如下:

-– package.json

-– src

- - - 图片

--------- 16张图片

------页

---------我要在其中渲染16张图像的页面

等等

谢谢。


阅读 355

收藏
2020-07-22

共1个答案

小编典典

在GraphiQL中戳一下应该可以帮助您,尤其是Explorer。尽管请记住,盖茨比片段在GraphiQL中不起作用。

{
  allImageSharp {
    edges {
      node {
        id
        fluid(maxWidth: 200, maxHeight: 200) {
            ...GatsbyImageSharpFluid
        }
      }
    }
  }
}

因此,上述内容应与类似以下查询的内容相同, 它将 在GraphiQL中工作

{
  allImageSharp {
    edges {
      node {
        id
        fluid(maxHeight: 200, maxWidth: 200) {
          src
          srcSet
          base64
          aspectRatio
          originalImg
          sizes        
        }
      }
    }
  }
}

然后,您的组件可以使用相同的查询并呈现如下结果:

import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"

const imgGridStyle = {
  display: 'grid',
  gridTemplateColumns: `repeat(auto-fill, 200px)`
};

export default ({ data }) => (
  <div>
    <h1>Hello gatsby-image</h1>
    <div style={imgGridStyle}>
      {data.allImageSharp.edges.map(edge => 
        <Img fluid={edge.node.fluid} />
      )}
    </div>
  </div>
)

export const query = graphql`
  query {
    allImageSharp {
      edges {
        node {
          id
          fluid(maxWidth: 200, maxHeight: 200) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
`

您可以轻松遍历查询中返回的imageSharp节点的结果数组data.allImageSharp.edges.map。然后将每个节点的fluid属性作为属性传递fluidgatsby- image

注意:这将呈现项目中的 每个 imageSharp节点,这可能是您实现的,也可能不是。

2020-07-22