我使用GatsbyJS
,并试图根据URL的路由呈现不同的header
。
例子:
mydomain.com/
=>应该呈现HeaderLanding
mydomain.com/blog
=>应该呈现HeaderMain
有人知道根据layout.js
文件中的路由创建条件呈现以显示组件的正确方法吗?
谢谢您一直鼓励我。
// layout.js
import React from "react"
import PropTypes from "prop-types"
import HeaderLanding from "./header-landing"
import HeaderMain from "./header-main"
import Footer from "./footer"
const Layout = ({ children }) => {
return (
<>
<Header/>
<div className="content-wrapper">
<main>{children}</main>
</div>
<Footer/>
</>
)
}
export default Layout
发布于 2019-08-10 07:53:45
@ravibagul91 91已经回答了很多问题,但是盖茨比并没有使用react-router-dom
。
如果Layout
是一个页面组件,那么盖茨比会给它传递一个location
道具。您可以提取location.pathname
并在那里应用您的逻辑
const Layout = ({ children, location }) => {
const isMain = location.pathname === 'your-path'
return (
<>
{ isMain ? <HeaderMain> : <HeaderLanding> }
<div className="content-wrapper">
<main>{children}</main>
</div>
<Footer/>
</>
)
}
export default Layout
如果Layout
不是页面组件,则可以从@reach/router
导入特殊的Location
。
import { Location } from '@reach/router' // gatsby's dep
const Layout = ({ children }) => {
return (
<Location>
{({ location }) => (
...
)}
</Location>
)
}
或者简单地将location
道具从Gatsby页面组件传递到每个页面中的该组件:
import Layout from '../components/layout'
export default ({ location }) => (
<Layout location={location}>
...
</Layout>
)
发布于 2019-08-10 07:06:31
您可以使用location
对象的withRouter
自组织。
import { withRouter } from 'react-router-dom';
const Layout = ({ children, location }) => {
return (
<>
{location.pathname.split('/')[1] ==="blog" ? <HeaderMain /> : <HeaderLanding /> }
<div className="content-wrapper">
<main>{children}</main>
</div>
<Footer/>
</>
)
}
export default withRouter(Layout)
更新
Gatsby v2用@reach/router
从react-router
切换路由器
从文档,
在v1中,布局组件可以访问历史记录、位置和匹配道具。在v2中,只有页面可以访问这些道具。如果在布局组件中需要这些道具,请从页面中传递它们。
所以你的Layout
组件应该是
const Layout = ({ children, location }) => {
return (
<>
{location.pathname.split('/')[1] ==="blog" ? <HeaderMain /> : <HeaderLanding /> }
<div className="content-wrapper">
<main>{children}</main>
</div>
<Footer/>
</>
)
}
export default Layout
您的Page
组件应该是,(仅举个例子)
import React from "react"
import Layout from "../components/layout"
export default props => (
<Layout location={props.location}> //Pass location here
<div>Hello World</div>
</Layout>
)
或你可以使用Location
。
通常,您只能访问路由组件中的位置,location为您的应用程序中的任何位置提供了一个子渲染支持。
<Location>
{props => {
props.location
props.navigate
}}
</Location>
// usually folks use some destructuring
<Location>
{({ location })=> {
// ...
}}
</Location>
https://stackoverflow.com/questions/57443187
复制相似问题