【问题标题】:How to access context variable within the template component in Gatsby?如何在 Gatsby 的模板组件中访问上下文变量?
【发布时间】:2019-11-10 11:33:31
【问题描述】:

在 Gatsby 应用程序的反应组件中,我了解如何在 graphql 查询中使用上下文变量,例如:

export const tagPageQuery = graphql`
  query TagPage($tag: String) {
    site {
      siteMetadata {
        title
      }
    }
    allItem(filter: { tags: { in: [$tag] } }) {
      totalCount
      edges {
        node {

          id
          move
          videoUrl

$tag 是一个允许我过滤的字符串。我明白了。但是有没有办法在组件本身中访问这个值?我可以访问 graphql 查询获取的数据,但无法获取 Graphql 之外的变量。我希望它是{context.tag} 或类似的东西,以便能够在我的h1 中使用该值。我已经通过Gatsby GraphQL reference 并且没有骰子。感觉获得这个值应该很容易,但我想知道是否需要使用类似 getContext 的钩子?

【问题讨论】:

    标签: reactjs graphql gatsby


    【解决方案1】:

    10 分钟小睡的效果真是太棒了!实际上,您可以使用此处详述的 pageContext 属性访问上下文变量:https://www.gatsbyjs.org/docs/creating-and-modifying-pages/#creating-pages-in-gatsby-nodejs

    const TagPage = ({ data, classes , pageContext}) => {
    

    将 pageContext 添加到我的道具允许我访问$tag

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 2020-12-08
      • 2017-07-23
      • 1970-01-01
      相关资源
      最近更新 更多