我目前在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的道具来渲染图像?
答案 0 :(得分:1)
除非我有误解,否则我认为您无需更改查询即可实现。只需将每个查询的结果作为道具传递给子组件即可。
// 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
}
}
`
这里是{{3}}来测试以上内容。
答案 1 :(得分:1)
您可以像这样将变量传递给GraphQL查询:
export const pageQuery = graphql`
query image($src: String!) file(relativePath: { eq: $src }) {
...fluidImage
}`
这是一个如何Pass Variable
的示例