我想在某些路由中隱藏頁眉和頁腳組件,例如;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 />
然后 Header 和 Footer 也會被渲染。但我想為這條特定的路線隱藏它們。那么我該怎么做呢?
我正在使用 react-router 版本 5
uj5u.com熱心網友回復:
這取決于應該渲染 Header 和 Footer 組件的頁面數量。如果您只想在幾頁上呈現它們,最簡單的解決方案是將它們移動到您想要呈現它們的組件/頁面。
如果您只想將它??們隱藏在一兩個地方,您可以使用useRouteMatch掛鉤。
您還可以構建一些抽象來簡化可讀性:讓我們制作一個Layout組件,它將接受一個道具(例如renderHeaderAndFooter(您當然可以更改名稱??))。
布局組件:
const Layout = ({ renderHeaderAndFooter, children }) => (
<div>
{renderHeaderAndFooter && (
<Header />
)}
{children}
{renderHeaderAndFooter && (
<Footer />
)}
</div>
)
和使用地點:
const HomeScreen = () => (
<Layout renderHeaderAndFooter={true}>
// make stuff
</Layout>
)
const Invoices = () => (
<Layout renderHeaderAndFooter={false}>
// make stuff
</Layout>
)
uj5u.com熱心網友回復:
簡單的方法是通過在您想要的每個組件中使用 useRouteMatch 來觸發您當前的路線,例如:
const match = useRouteMatch("/invoice/:id/print"); // import { useRouteMatch } from "react-router-dom";
return !!match ? <></> : <Footer/> //or Header
檢查這個
uj5u.com熱心網友回復:
您必須在組件的渲染階段通過添加偵聽器來更新 Header 和 Footer 組件:componentDidMount()
獲取被呼叫的組件: const shouldHide = useRouteMatch("/invoice/:id/print") || useRouteMatch("/other/route");
return (
!shoudlHide && <Header />
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468920.html
上一篇:如何呼叫異步清理函式?
