在 Gatsby 上,如何使用 prop 进行 GraphQL 查询?

Ric*_*eis 3 reactjs graphql gatsby

我正在将一个道具传递给一个新组件并尝试使用它来执行 graphql 查询。它看起来像这样。

import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import Img from "gatsby-image"

const ComponentName = props => {
  const getImage = graphql`
{
  image: file(relativePath: { eq: ${props.img} }) {
    childImageSharp {
      fluid {
        ...GatsbyImageSharpFluid
      }
    }
  }
}
`
  const data = useStaticQuery(getImage)
  return (
    <li>
      <Img
        fluid={data.image.childImageSharp.fluid}
      />
    </li>
  )
}

export default ComponentName
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误 BabelPluginRemoveGraphQLQueries: String interpolations are not allowed in graphql fragments. Included fragments should be referenced as...MyModule_foo.

我尝试了各种不同的技巧来摆脱“字符串插值”错误。但是它们都不起作用(它只是每次都显示不同的错误)。

我假设您不能使用 props 进行 graphql 查询?或者有另一种方法可以做到这一点?

Den*_*ash 5

StaticQuery文档

StaticQuery 不接受变量(因此称为“静态”),但可以在任何组件中使用,包括页面。

钩子版本useStaticQuery也一样:

useStaticQuery 不接受变量(因此称为“静态”),但可以在任何组件中使用,包括页面。

您可以在 gatsby 的 GitHub此处进一步阅读。