【问题标题】:How do I create a fragment for a Gatsby StaticQuery Hook?如何为 Gatsby StaticQuery Hook 创建片段?
【发布时间】:2020-01-27 03:49:12
【问题描述】:

我正在尝试为 Gatsby JS 中的 StaticQuery 钩子创建一个片段,但我不确定如何创建它。我尝试像这样创建另一个片段变量:

const fixedImage = graphql`
    fragment fixedImage on File {
        childImageSharp{
            fixed{
                ...GatsbyImageSharpFixed
            }
        }
    }
    `

但我的查询仍然找不到片段,我也尝试将其作为参数传递,如下所示,但无济于事。

const data = ({fixedImage}) => useStaticQuery(graphql`
query MyQuery {
  square1: file{
    ...fixedImage
  }
  square2: file{
    ...fixedImage
  }
  square3: file{
    ...fixedImage
  }
  square4: file{
    ...fixedImage
  }
}
`)

【问题讨论】:

    标签: reactjs graphql gatsby


    【解决方案1】:

    您需要在组件中导出片段查询。哪个组件无关紧要,但最好将其导出到相关组件(即 Image.jsx)中。

    Image.jsx:

    import React from "react"
    import { graphql } from "gatsby"
    import Image from "gatsby-image"
    
    export default ({ image }) => (
      <div>
        <Image fixed={image.childImageSharp.fixed} />
      </div>
    )
    export const query = graphql`
      fragment fixedImage on File {
            childImageSharp{
                fixed{
                    ...GatsbyImageSharpFixed
                }
            }
        }
    `
    

    然后你可以在其他组件中使用片段。

    Post.jsx:

    import React from "react"
    import { graphql } from "gatsby"
    import Image from "./Image.jsx"
    
    export default () => {
    const data = useStaticQuery(query)
    const { square1 } = data
    
     return (
       <div>
         <Image image={square1} />
       </div>
      )
    }
    
    const query = graphql`
        query MyQuery {
            square1: file(absolutePath: { regex: "/square1.(jpeg|jpg|gif|png)/" }) {
                ...fixedImage
            }
        }
    `
    

    更多关于 Gatsby 片段的信息:https://www.gatsbyjs.org/docs/using-graphql-fragments/

    【讨论】:

      【解决方案2】:

      我对 Gatsby Image 也有同样的问题;我想减少每次调用 childImageSharp 的重复。 我通过在这样的查询之前创建内联片段来解决它:

      const data = useStaticQuery(graphql`
          fragment fluidImage on File {
              childImageSharp {
                  fluid(maxWidth: 1000) {
                    ...GatsbyImageSharpFluid
                  }
              }
          }
          query {
            imageOne: file(relativePath: { eq: "img/image1.jpg" }) {
              ...fluidImage
            }
            imageTwo: file(relativePath: { eq: "img/image2.jpg" }) {
              ...fluidImage
            }
            imageThree: file(relativePath: { eq: "img/image3.jpg" }) {
              ...fluidImage
            }
          }
        `);
      

      【讨论】:

        猜你喜欢
        • 2020-12-06
        • 2021-04-05
        • 2023-04-01
        • 2020-11-12
        • 1970-01-01
        • 2023-03-25
        • 2020-11-16
        • 2014-01-25
        • 2020-03-13
        相关资源
        最近更新 更多