【问题标题】:How do I query for gatsby-image?如何查询 gatsby-image?
【发布时间】:2020-06-09 17:36:26
【问题描述】:

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

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

【问题讨论】:

标签: reactjs gatsby prismic.io gatsby-image


【解决方案1】:

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

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

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

// ./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" 并将相关的查询值传递给 &lt;Img /&gt; 组件的固定或流体属性。

// ./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
            }
          }
        }
      }
    }
  }
`

【讨论】:

    猜你喜欢
    • 2019-10-19
    • 2021-06-05
    • 2020-09-08
    • 2023-04-06
    • 2019-07-15
    • 2020-09-30
    • 2021-06-20
    • 2020-06-09
    • 1970-01-01
    相关资源
    最近更新 更多