首页 > 解决方案 > 如何查询 gatsby-image?

问题描述

我正在尝试查询棱镜单一类型以通过 gatsby-image 显示照片。在 GraphiQL 中搞乱之后,我看到了图像 url,但我不确定如何将其插入 gatsby-image。有什么建议吗?在此处输入图像描述

  <Layout 
    location={`home`}
    image={data.prismic._allDocuments.edges.node.hero_image.childImageSharp.fluid}
  >

标签: reactjsgatsbyprismic.iogatsby-image

解决方案


任何时候你在 GraphQL 中看到前缀all,你都应该假设它会返回一个数组。

GraphQL我们可以看到_allDocuments.edges返回一个数组edges如果我们想显示该数组中的所有内容,我们需要对其进行映射。

如果我们知道我们想要的单个事物的索引,我们可以使用括号符号直接访问它。

// ./pages/index.js

import React from "react"
import Layout from "../components/layout"


const IndexPage = ({data}) => {
  return (
  <Layout>
    <ul>
      {data.allFile.edges.map((edge) => (
        <li>{edge.node.name}</li>
      ))}
    </ul>
  </Layout>
)}

export default IndexPage


export const query = graphql`
  query HomePageQuery {
    allFile(filter: {relativePath: {regex: "/png$/"}}) {
      edges {
        node {
          id
          name
          relativePath
          publicURL
          childImageSharp {
            fixed(width: 111) { 
              ...GatsbyImageSharpFixed
            }
          }
        }
      }
    }
  }
`

然后您可以import Img from "gatsby-image"将相关的查询值传递给<Img />组件的固定或流体道具。

// ./pages/index.js

import React from "react"
import Layout from "../components/layout"
import Img from "gatsby-image"


const IndexPage = ({data}) => {
  return (
  <Layout>
      {data.allFile.edges.map((edge) => (
        <Img fixed={edge.node.childImageSharp.fixed} />
      ))}
  </Layout>
)}

export default IndexPage



export const query = graphql`
  query HomePageQuery {
    allFile(filter: {relativePath: {regex: "/png$/"}}) {
      edges {
        node {
          id
          name
          relativePath
          publicURL
          childImageSharp {
            fixed(width: 111) { 
              ...GatsbyImageSharpFixed
            }
          }
        }
      }
    }
  }
`

推荐阅读