[英]Component inside component in React Router
我正在嘗試在 React Router 中使用 Mantine 的應用程序 shell ( https://mantine.dev/core/app-shell/ ) 使其僅在特定路由上啟用。
這怎么可能實現。
通常,要顯示一個組件,我會執行以下操作,例如:
<Route element={<SidebarLayout {...{ inactive, setInactive }} />}>
<Route path="/" element={<Main />} />
但在這種情況下,我得到了更多代碼(基於文檔中的示例) - 我計划在這個<AppShell>
組件中添加一個組件(請一直向下看):
<AppShell
styles={{
main: {
background:
theme.colorScheme === "dark"
? theme.colors.dark[8]
: theme.colors.gray[0],
},
}}
navbarOffsetBreakpoint="sm"
asideOffsetBreakpoint="sm"
navbar={
<Navbar
p="md"
hiddenBreakpoint="sm"
hidden={!opened}
width={{ sm: 200, lg: 300 }}
>
<Text>Application navbar</Text>
</Navbar>
}
aside={
<MediaQuery smallerThan="sm" styles={{ display: "none" }}>
<Aside p="md" hiddenBreakpoint="sm" width={{ sm: 200, lg: 300 }}>
<Text>Application sidebar</Text>
</Aside>
</MediaQuery>
}
footer={
<Footer height={60} p="md">
Application footer
</Footer>
}
header={
<Header height={70} p="md">
<div
style={{ display: "flex", alignItems: "center", height: "100%" }}
>
<MediaQuery largerThan="sm" styles={{ display: "none" }}>
<Burger
opened={opened}
onClick={() => setOpened((o) => !o)}
size="sm"
color={theme.colors.gray[6]}
mr="xl"
/>
</MediaQuery>
<Text>Application header</Text>
</div>
</Header>
}
>
<Text>Resize app to see responsive navbar in action</Text> <-- PLANNING TO ADD COMPONENT HERE BASED ON ROUTE
</AppShell>
我怎樣才能將整個事情集成到 React Router 中?
正如“SidebarLayout”的名字所暗示的,你問的是如何實現所謂的布局路由。 布局路由通常會渲染一些常見的邏輯和 UI 元素/組件,以及用於嵌套路由的Outlet組件以將其內容渲染到其中。 您通常會在通常渲染children
道具的地方渲染Outlet
組件。
例子:
在Text
組件下方渲染一個Outlet
。
<AppShell
...
>
<Text>Resize app to see responsive navbar in action</Text>
<Outlet /> // <-- render Outlet here for nested routes
</AppShell>
用法:
<Routes>
<Route element={<SidebarLayout {...{ inactive, setInactive }} />}>
<Route path="/" element={<Main />} />
... other routes with SidebarLayout ...
</Route>
... other routes w/o SidebarLayout ...
</Routes>
這可以通過兩種方式完成:
通過在wrapper
function 中加載AppShell
組件,您可以通過基於route
路徑傳遞子組件來包裝子組件。
wrapper
組件,我們將其withAppShell
組件,現在您可以按如下方式加載它:export const withAppShell = (ChildComponent) =>
(
<AppShell ... // App Shell code start
<ChildComponent /> // the part where you wish to load your child component
</AppShell> // App Shell code end
)
withAppShell(ChildComponent);
感覺和第一個差不多,但不是——
export const AppShellWrapper = ({children}) =>
(
<AppShell ... //start
{children}
</AppShell> //end
)
<AppShellWrapper>
<ChildComponent />
</AppShellWrapper>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.