在Gatsby中将字符串传递给GraphQL StaticQuery [英] Pass string to a GraphQL StaticQuery in Gatsby

查看:92
本文介绍了在Gatsby中将字符串传递给GraphQL StaticQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解StaticQuery如何在Gatsby/GraphQL工作流程中工作,并且作为一个试用版,我想构建一个带有背景图片的文章标题.

I am trying to understand how StaticQuery works in a Gatsby/GraphQL workflow, and as a trial I want to build an article header with a background image.

该图像在我从(frontmatter.feature)构建的降价文件的最前面定义.

The image is defined in frontmatter of the markdown file I am building from (frontmatter.feature).

我知道StaticQuery的本质是……很好……是静态的,因此我无法将动态变量传递给查询.但这不是我在做的-我想.

I know the nature of StaticQuery is... well... static, so I cannot pass dynamic variables to a query. But that's not what I am doing - I think.

这是我的例子:

articleHeader(frontmatter) {
  if (frontmatter.feature) {
    return (
      <StaticQuery
        query={graphql`
          query($base: String!) {
            file(base: { eq: $base }) {
              publicURL
            }
          }
        `}
        render={data => (
          <ArticleHeader
            style={"background-image:url(" + data.file.publicURL + ")"}
          >
            <Heading>{frontmatter.title}</Heading>
          </ArticleHeader>
        )}
      />
    );
  } else return <Heading>{frontmatter.title}</Heading>;
}

我的问题是我想将frontmatter.feature传递给查询,以便我可以查询base: { eq: $base } ...但是如何?

My problem is that I want to pass frontmatter.feature to my query so that I can query for base: { eq: $base } ... but how?

注意:我已经正确设置了插件,并且可以通过graphiql界面查询文件而没有问题.

Note: I've set up plugins properly, and I can query for files through the graphiql interface without issues.

推荐答案

如果修改frontmatter.feature使其成为图像的相对路径,它将变成File节点,这意味着您可以查询在您查询frontmatter的任何地方:

If you modify frontmatter.feature so that it's a relative path to your image, it will turn into a File node, meaning you can query the publicURL in wherever you query for frontmatter:

export const query = graphql`
  allMarkdownRemark {
    nodes {
      frontmatter {
        title
        feature {
          publicURL
        }
      }
    }
  }
`

然后,您的文章标题组件就可以

Then, your article header component can simply be

const ArticleHeader = ({ frontmatter }) => {
  const { title, feature } = frontmatter
  if (!feature) return <Heading ... />
  return (
    <div style={`background-image:url(${feature.publicURL})`}>
      <Heading ...>
    </div>
  )
}

这篇关于在Gatsby中将字符串传递给GraphQL StaticQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆