首页 > 解决方案 > 如何在 gatsby 的布局文件中获取路径名

问题描述

我正在使用gasby,这里的主文件始终layout.js是它们的父文件。既然它是一个父文件,那么我怎样才能this.props.location.pathname在其中获取位置道具?

这是我的布局组件

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.

标签: javascriptreactjsreact-routergatsby

解决方案


正如盖茨比文档中所述:

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

这意味着您需要转到 Layout 组件的渲染位置,通常是 index.js 或 app.js 页面,并将 location 属性直接传递给它:

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

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

然后你可以在你的布局中使用它。您还可以在此处阅读更多内容。


推荐阅读