如何使用道具字符串将值传递给StaticQuery?

EdB*_*ker 5 javascript reactjs graphql gatsby react-props

我正在 Gatsby.js 中开发一个网站,其中包含一个博客并用于帖子布局,我正在使用由帖子作者设置的背景图像对这个标题进行编码。我仍处于设计阶段,放置元素,空白文本等。

我已经使用 BackgroundImage、graphQL 和 StaticQuery 制作了这个组件,并且在它的代码中,如果我用“post_8.jpg”文本缩小对来自 gatsby-source-filesystem 的图像的搜索范围,它应该可以正常工作。

import React from 'react'
import { graphql, StaticQuery } from 'gatsby'
import BackgroundImage from 'gatsby-background-image'
import TextScramble from './TextScramble'


const BackgroundDiv = ({ className, children }) => (
  <StaticQuery 
    query={graphql`
      query($post: String! ) {
        file(relativePath: {eq: "post_8.jpg"}) {
          childImageSharp {
            fluid {
              ...GatsbyImageSharpFluid
            }
          }
        }
        }
      `
    }
    render={data => {
      const imageData = data.file.childImageSharp.fluid
      return (
        <BackgroundImage
          Tag="div"
          className={className}
          fluid={imageData}
        >
    <h1 className="bg-white shaddow shadow-md py-1 px-4 w-auto inline-block text-4xl absolute bottom-0 mb-24"><TextScramble>{ children }</TextScramble></h1>
        </BackgroundImage>
      )}
    }
  />
)

export default BackgroundDiv
Run Code Online (Sandbox Code Playgroud)

但是,我想知道如何将包含帖子的页面的 frontmatter 中的值传递给该组件。

我一直在考虑使用传递给组件的值,例如postName. 例如:

const BackgroundDiv = ({ className, children, postName }) => (
Run Code Online (Sandbox Code Playgroud)

然后,它将在查询中以字符串形式获取此值。

query={graphql`
      query($post: String! ) {
        file(relativePath: {eq: ${postName}}) {
          childImageSharp {
            fluid {
              ...GatsbyImageSharpFluid
            }
          }
        }
        }
      `
    }
Run Code Online (Sandbox Code Playgroud)

我在上面做了这个简单的添加,但没有用。编译失败告诉我

String interpolation is not allowed in graphql tag:

    9 |     query={graphql`   
   10 |       query($postName: String! ) {
 > 11 |         file(relativePath: {eq: ${postName}}) {
      |                                ^^^^^^^^^^^   
   12 |           childImageSharp {   
   13 |             fluid {   
   14 |               ...GatsbyImageSharpFluid

 File: [$pathToFolder]/gatsby-theme-cripto/src/components/backgroundDiv.js
Run Code Online (Sandbox Code Playgroud)

我在谷歌上搜索过字符串插值问题,甚至在这里结束,但我无法将这些内容与我的问题联系起来。我不是经验丰富的开发人员,所以我相信我错过了一些东西。对此问题的任何想法都将不胜感激,就像我可以发布的任何代码请求一样,以帮助理解这个问题。

先感谢您!

小智 -1

我经历过类似的问题。幸运的是,我发现这可以与字符串插值一起使用:

// Option 1
$postName
const query1 = `file(relativePath: {eq: $postName}) { ... }`

// Option 2
${({postName})

const query2 = `file(relativePath: {eq: ${({postName})}) { ... }`
Run Code Online (Sandbox Code Playgroud)

看一下我用于我的一个项目的代码片段: https://github.com/timrodz/.com/blob/master/src/components/common/Button/index.js#L33