如何在Gatsby中获取布局文件中的路径名 [英] How to get pathname in the layout file in gatsby

查看:96
本文介绍了如何在Gatsby中获取布局文件中的路径名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gasby,这里的主文件始终是layout.js,这是所有文件的父文件.由于它是一个父文件,那么如何在其中获取位置道具this.props.location.pathname?

I am working with gasby and here the main file is always layout.js which is the parent of them all. Since it is a parent file then how can I get a location props this.props.location.pathname inside it?

这是我的布局组件

class Layout extends Component {
  componentWillMount() {
    console.log(this.props, 'dssssssssssssf')
  }

  render() {
    const { children } = this.props
    return(
      <StaticQuery
        query={graphql`
          query SiteTitleQuery {
            site {
              siteMetadata {
                title
              }
            }
          }
        `}
        render={data => (
          <>
            <div>
              <Provider store={store}>
                {children}
              </Provider>
            </div>
          </>
        )}
      />
    )
  }
}
Layout.propTypes = {
  children: PropTypes.node.isRequired
}

export default Layout.

推荐答案

如盖茨比文档所述:

在v1中,布局组件可以访问历史记录,位置和匹配项 道具.在v2中,只有页面可以访问这些道具.如果您需要这些 布局组件中的道具,将它们从页面传递出去.

In v1, the layout component had access to history, location, and match props. In v2, only pages have access to these props; if you need these props in the layout component, pass them through from the page.

这意味着您需要转到呈现Layout组件的位置(通常是index.js或app.js页面),然后将位置属性直接传递给它:

What this is means is that you need to go to where your Layout component is rendered, which will be the index.js or app.js page usually, and pass the the location props to it directly:

import React from "react"
import Layout from "../components/layout"

export default props => (
  <Layout location={props.location}>
    <div>Hello World</div>
  </Layout>
)

然后您可以在布局中使用它.您还可以在此处了解更多信息.

Then you can use it in your layout. You can also read more here.

这篇关于如何在Gatsby中获取布局文件中的路径名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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