问题描述
我正在使用 GatsbyJS
,并且尝试根据URL的路由呈现不同的 header
.
I'm using GatsbyJS
and I'm trying to render a different header
according to the route of the URL.
示例:
mydomain.com/
=>应该呈现 HeaderLanding
mydomain.com/blog
=>应该呈现 HeaderMain
有人知道根据 layout.js
文件中的路由创建条件渲染以显示组件的正确方法吗?
Does anyone know the proper way to create a conditional rendering to display a component according to the route in the layout.js
file?
感谢您的支持.
// 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
推荐答案
@ ravibagul91回答的内容差不多,但是Gatsby不使用 react-router-dom
.
Pretty much what @ravibagul91 have answered, however Gatsby doesn't use react-router-dom
.
如果 Layout
是页面组件,则Gatsby将为它传递一个 location
道具.您可以提取 location.pathname
&在那儿运用你的逻辑
If Layout
is a page component, Gatsby will pass it a location
prop. You can extract location.pathname
& apply your logic there
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
导入HOC Location
:
If Layout
is not a page component, you can import the HOC Location
from @reach/router
:
import { Location } from '@reach/router' // gatsby's dep
const Layout = ({ children }) => {
return (
<Location>
{({ location }) => (
...
)}
</Location>
)
}
或者只是将Gatsby页面组件中的 location
道具传递给每个页面中的该组件:
Or simply pass the location
props from a Gatsby page component to this component from each page:
import Layout from '../components/layout'
export default ({ location }) => (
<Layout location={location}>
...
</Layout>
)
这篇关于如何使用GatsbyJS根据路线渲染组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!