Pro*_*fer 2 javascript reactjs react-router 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.
Run Code Online (Sandbox Code Playgroud)
正如 Gatsby 文档中所述:
在 v1 中,布局组件可以访问历史记录、位置和匹配道具。在 v2 中,只有页面可以访问这些 props;如果您在布局组件中需要这些道具,请从页面传递它们。
这意味着你需要去你的 Layout 组件被渲染的地方,通常是 index.js 或 app.js 页面,并将位置道具直接传递给它:
import React from "react"
import Layout from "../components/layout"
export default props => (
<Layout location={props.location}>
<div>Hello World</div>
</Layout>
)
Run Code Online (Sandbox Code Playgroud)
然后你可以在你的布局中使用它。您还可以在此处阅读更多内容。
| 归档时间: |
|
| 查看次数: |
2705 次 |
| 最近记录: |