我正在使用 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/