重构 Gatsby 图像查询

Refactor Gatsby Image Query

我目前在我的 IndexPage 组件中使用 Gatsby 和 gatsby-image。我希望将下面的代码重构为单个 React 组件,因为没有不必要的重复:

          ...
          return (
          <div>
            <h1>Startups</h1>
            <p>Copy</p>
            <Img fluid={props.data.imageOne.childImageSharp.fluid}/>
          </div>
          <div>
            <h1>People</h1>
            <p>Copy</p>
            <Img fluid={props.data.imageTwo.childImageSharp.fluid}/>
          </div>
          <div>
            <h1>Data</h1>
            <p>Copy</p>
            <Img fluid={props.data.imageThree.childImageSharp.fluid}/>
          </div>
        </div>
        )

export const fluidImage = graphql`
fragment fluidImage on File {
  childImageSharp {
    fluid(maxWidth: 1000) {
      ...GatsbyImageSharpFluid
    }
  }
}
`

export const pageQuery = graphql`
  query {
    imageOne: file(relativePath: { eq: "igemA.png" }) {
      ...fluidImage
    }
    imageTwo: file(relativePath: { eq: "inephemeraA.png" }) {
      ...fluidImage
    }
    imageThree: file(relativePath: { eq: "polypA.png" }) {
      ...fluidImage
    }
  }

类似于这样的东西:

const NewComponent = (props) => (
          <div>
            <h1>props.heading</h1>
            <p>props.body</p>
            <Img fluid={props.data.[props.image].childImageSharp.fluid}/>
          </div>

)

如何更改 graphql 查询,以便根据传递给 NewComponent 的道具渲染图像?

除非我有误解,否则我认为您不需要更改查询即可完成此操作。只需将每个查询的结果作为 prop 传递给您的子组件。

// components/newComponent.js

import React from "react"
import Img from "gatsby-image"

const NewComponent = ({ image, heading, body }) => (
  <>
    <h1>{ heading }</h1>
    <p>{ body }</p>
    <Img fluid={ image.childImageSharp.fluid } />
  </>
)

export default NewComponent

// index.js

import React from "react"
import {graphql} from "gatsby"

import NewComponent from "../components/newComponent"

const IndexPage = ({ data }) => {
  const { imageOne, imageTwo } = data
  return (
  <>
    <NewComponent image={ imageOne } heading="heading 1" body="body 1" />
    <NewComponent image={ imageTwo } heading="heading 1" body="body 2" />
  </>
)}

export default IndexPage

export const fluidImage = graphql`
fragment fluidImage on File {
  childImageSharp {
    fluid(maxWidth: 1000) {
      ...GatsbyImageSharpFluid
    }
  }
}
`

export const pageQuery = graphql`
  query {
    imageOne: file(relativePath: { eq: "gatsby-astronaut.png" }) {
      ...fluidImage
    }
    imageTwo: file(relativePath: { eq: "gatsby-icon.png" }) {
      ...fluidImage
    }
  }
`

这里有一个 CodeSandbox 来测试上面的内容。

您可以像这样将变量传递给 GraphQL 查询:

export const pageQuery = graphql`
  query image($src: String!) file(relativePath: { eq: $src }) {
      ...fluidImage
    }`

这是一个如何Pass Variable

的例子