[英]React: how to hide a component on certain pages
How do i hide certain components on certain pages in my app?如何在我的应用程序的某些页面上隐藏某些组件? Specifically I need to hide Navbar and Header from the Settings page.具体来说,我需要从“设置”页面隐藏导航栏和标题。
in App.js i set up a router:在 App.js 中,我设置了一个路由器:
<div>
<Router>
<Switch>
<Header/> <- header and navbar are here
<Navbar/>
<Route exact path = "/" component= { Data } />
<Route path = "/available-data" component= { Data } />
<Route path = "/devices" component= { Devices } />
<Route path = "/contacts" />
<Route path = "/chat" />
<Route path = "/settings" component = { Settings } /> <- i need to remove them from here
</Switch>
</Router>
</div>
Header and Navbar are used in every component except in Settings. Header 和 Navbar 用于除设置之外的每个组件。 How do i go about removing/hiding them?我该如何移除/隐藏它们?
All three of the files are function components with useState hooks(if they even have state) if it matters :)如果重要的话,所有三个文件都是带有 useState 钩子的函数组件(如果它们甚至有状态):)
You can render a second switcher component to only route to pages with the header and navbar UI.您可以渲染第二个切换器组件以仅路由到带有标题和导航栏 UI 的页面。
// in App.js
<div>
<Router>
<Switch>
<Route exact path="/settings" component={Settings} />
<Route path='/' ><UiRouter /></Route>
</Switch>
</Router>
</div>
// in UiRouter.js
export default function UiRouter() {
return (
<>
<Header />
<Navbar />
<Switch>
<Route exact path="/" component={Data} />
<Route path="/available-data" component={Data} />
<Route path="/devices" component={Devices} />
<Route path="/contacts" component={Contacts}/>
<Route path="/chat" component={Chat}/>
</Switch>
</>
);
}
Also, as Ajith mentioned, you should not have the components that you want to render for each route (Header and Navbar) inside the Switch component.此外,正如 Ajith 所提到的,您不应该在 Switch 组件中为每个路由(Header 和 Navbar)渲染组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.