19

我在盖茨比中有这个页面:

import React from 'react'
import Link from 'gatsby-link'

import IntroPartial from '../partials/themes/intro'

export default class ThemeTemplate extends React.Component {
  render(){
    const theme = this.props.pathContext.theme
    console.dir(this.data)
    return (
      <div>
        <h1>{theme.name}</h1>
        <IntroPartial theme={theme} />
      </div>
    )
  }
}

export const pageQuery = graphql`
query ThemeQuery($theme: String){
  allMarkdownRemark(
    filter: { frontmatter: { themes: { in: [$theme] } } }
  ){
    edges{
      node{
        frontmatter{
          title
          themes
        }
        html
      }
    }
  }
}
`

假设我提供了$theme. 我如何提供价值$theme?我想将其设置为this.props.pathContext.theme.slug.

文档似乎暗示某些变量应该可以工作,但我不确定如何添加我自己的。

4

1 回答 1

28

传递给 graphql 的变量来自createPage。它通常在您的 gatsby-node 文件中调用。您经常会在需要的示例中看到使用的路径,如 $path。

为了包含您自己的附加变量以传递给 graphql 调用,您需要将它们添加到上下文中。稍微修改一下文档中的示例:

createPage({
  path: `/my-sweet-new-page/`,
  component: path.resolve(`./src/templates/my-sweet-new-page.js`),
  // The context is passed as props to the component as well
  // as into the component's GraphQL query.
  context: {
   theme: `name of your theme`,
 },
})

然后,您可以像在示例中一样在查询中使用 $theme。在上面的代码中设置 $theme 将在createPages部分(参见示例)中完成,因为您将可以访问所有数据。

于 2017-09-24T00:11:35.600 回答