javascript - 如何在 gatsby 中获取布局文件中的路径名

标签 javascript reactjs react-router gatsby

我正在使用 gasby,这里的主文件始终是 layout.js,它是所有文件的父文件。既然它是一个父文件,那么如何在其中获取位置 Prop 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.

最佳答案

如 Gatsby 文档中所述:

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.

这意味着您需要转到您的布局组件呈现的位置,通常是 index.js 或 app.js 页面,并直接将位置 Prop 传递给它:

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

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

然后你就可以在你的布局中使用它了。您还可以阅读更多here .

关于javascript - 如何在 gatsby 中获取布局文件中的路径名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55631403/

相关文章:

javascript - 使用组件 react 路由(PageRenderer)

javascript - 在React中使用react-router时组件消失

javascript - jQuery 键盘 z-index 模式对话框问题

javascript - 如何在 opera mini mobile 中将当前页面重定向到另一个页面?

ReactJs:为具有相同组件的选项卡维护单独的状态

javascript - React 协调中的令人惊讶的行为。为什么状态没有被重置?

javascript - 如何防止我的产品列表在父组件更新时重新呈现?

带有单个管道的 Javascript 条件语句 "|"

javascript - Geddy.js - 在没有布局的情况下渲染部分 View ,可能吗?

node.js - API 抓取应该是前端还是后端?