SolidJS Router:如何在嵌套路由中渲染固定侧边栏?
解决React嵌套路由公共侧边栏问题
React Router v6(当前主流版本)的嵌套路由写法和旧版本存在差异,你之前的写法不符合v6规范,导致无法生效。以下是两种可行的实现方案:
方案一:顶层路由直接配置嵌套结构
直接在顶层<Routes>中定义/profile的嵌套路由,通过<Outlet>渲染子路由内容,同时固定显示侧边栏:
import { Router, Routes, Route, Outlet } from 'react-router-dom'; function App() { return ( <Router> <div className="some wrap elements"> <header> {/* 头部菜单、Logo等,所有页面可见 */} </header> <div className="some container"> <Routes> <Route path="/" element={<Home />} /> {/* 父路由:渲染侧边栏 + 子路由占位符 */} <Route path="/profile" element={ <div className="another wrap elements"> <div className="sidebar">用户处于/profile、/profile/settings等页面时,侧边栏保持显示</div> {/* Outlet用于渲染子路由的具体内容 */} <Outlet /> </div> }> {/* 子路由:路径为相对路径,自动拼接父路由path */} <Route index element={<Profile />} /> {/* 对应 /profile 路径 */} <Route path="settings" element={<Settings />} /> {/* 对应 /profile/settings */} <Route path="favorites" element={<Favorites />} /> {/* 对应 /profile/favorites */} </Route> {/* 其他路由 */} </Routes> </div> </div> </Router> ); }
方案二:封装到Profile组件中(相对路由写法)
如果想把侧边栏和子路由逻辑封装在Profile组件内,需要让顶层路由匹配所有/profile开头的路径,再在组件内用相对路径定义子路由:
顶层路由修改:
<Routes> <Route path="/" element={<Home />} /> {/* 匹配所有/profile开头的路径,指向Profile组件 */} <Route path="/profile/*" element={<Profile />} /> {/* 其他路由 */} </Routes>
Profile组件写法:
import { Routes, Route } from 'react-router-dom'; function Profile() { return ( <div className="another wrap elements"> <div className="sidebar">用户处于/profile相关页面时,侧边栏保持显示</div> <Routes> <Route index element={<ProfileMain />} /> {/* 对应 /profile */} <Route path="settings" element={<Settings />} /> {/* 对应 /profile/settings */} <Route path="favorites" element={<Favorites />} /> {/* 对应 /profile/favorites */} </Routes> </div> ); }
你之前写法的问题说明
- 在Profile组件中使用
/profile/settings这种绝对路径,会和顶层路由的/profile规则冲突,应该改用相对路径(去掉前缀/profile) - React Router v6已废弃
component属性,需改用element={<组件 />}的方式指定路由组件 - 嵌套路由必须通过
<Outlet>来渲染子路由内容,否则子组件无法正常显示
内容的提问来源于stack exchange,提问作者Pasha Zozulia
相关产品推荐
相关产品推荐

