如何隐藏某些路线的某些组件
我想在某些路线中隐藏标题和页脚组件,e; g for path =“/invoice/:id/print”
我使用react-router-dom v5具有此类型的布局的应用程序
<Router>
<Header />
<main className="py-0 px-0">
<div>
<Container fluid>
<Switch>
<Route path="/" component={HomeScreen} exact />
<Route path="/invoices" component={Invoices} exact />
<Route path="/invoice/:id/print" component={InvoicePrint} exact />
<Route path="/billing/invoice/create" component={InvoiceCreate} exact />
<Route path="*" exact>
<Error404 />
</Route>
</Switch>
</Container>
</div>
</main>
<Footer />
</Router>
问题是,如果我去找
<Route path="/invoice/:id/print" component={InvoicePrint} exact />
标题和页脚也会渲染。但是我想将它们隐藏在此特定路线上。那我该怎么做呢?
我正在使用React-Router版本5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于应渲染标题和页脚组件的几页。
如果您只想在几页上渲染它们,最简单的解决方案将是将它们移至您想要渲染的组件/页面。
如果您只想将它们隐藏在一个或两个地方,则可以使用
useroutematch
钩子。您还可以构建一些摘要来简化可读性:让我们制作
布局
组件,该组件将接受Prop(例如renderheadsheaderanderandfooter
(您可以更改当然的名称That depends on how many pages should render the Header and Footer components.
If you want to render them on just a few pages, the simplest solution will be to move them to the components/pages where you'd like to render them.
If you'd like to hide them in just one or two places you can use the
useRouteMatch
hook.You can also build some abstractions to simplify the readability a bit: let's make the
Layout
component, which will accept a prop (likerenderHeaderAndFooter
(you can change the name of course ????)).Layout component:
and the place of usage:
简单的方法是通过在所需的每个组件中使用userOuteMatch触发当前路线,例如:
check
simple way is to trigger your current route by using useRouteMatch in every component you want like:
check this
您必须在组件的渲染阶段添加侦听器来更新标题和页脚组件:
componentdidmount()
fetch at the nater component:
const应该=用户outematch(“/invoice/:id/print”)|| UserOuteMatch(“/其他/路由”);
You have to update the Header and Footer components by adding a listener during the rendering phase of the component :
componentDidMount()
Fetch the called component :
const shouldHide = useRouteMatch("/invoice/:id/print") || useRouteMatch("/other/route");