React Router 的嵌套路由功能允许在路由内部定义更多路由,从而创建复杂、动态的应用布局。这对于构建包含子路由模块的应用(如仪表盘、用户配置或管理面板)至关重要。嵌套路由有助于建立分层 URL 结构,每个路由在其父组件内呈现特定内容。
在 React Router 中配置嵌套路由,需要在父路由中使用
以下示例展示了父路由和嵌套路由的定义:
import React from 'react'; import { BrowserRouter, Routes, Route, Link, Outlet } from 'react-router-dom'; // 父组件 const Dashboard = () => { return ( <div> <h2>仪表盘</h2> <nav> <ul> <li><Link to="profile">个人资料</Link></li> <li><Link to="settings">设置</Link></li> </ul> </nav> <hr /> <Outlet /> {/* 子路由内容渲染在此处 */} </div> ); }; // 子组件 const Profile = () => <h3>个人资料页面</h3>; const Settings = () => <h3>设置页面</h3>; const App = () => { return ( <BrowserRouter> <Routes> {/* 父路由 */} <Route path="dashboard" element={<Dashboard />}> {/* 嵌套路由 */} <Route path="profile" element={<Profile />} /> <Route path="settings" element={<Settings />} /> </Route> </Routes> </BrowserRouter> ); }; export default App;
嵌套路由也可以使用动态参数:
import React from 'react'; import { BrowserRouter, Routes, Route, Link, Outlet, useParams } from 'react-router-dom'; const Dashboard = () => { // ... (same as before) }; const Profile = () => { const { id } = useParams(); // 从 URL 获取 'id' 参数 return <h3>用户 {id} 的个人资料页面</h3>; }; const App = () => { return ( <BrowserRouter> <Routes> <Route path="dashboard" element={<Dashboard />}> {/* 带路径参数的嵌套路由 */} <Route path="profile/:id" element={<Profile />} /> </Route> </Routes> </BrowserRouter> ); }; export default App;
React Router 支持设置默认嵌套路由,当没有匹配到特定子路由时,渲染默认组件:
import React from 'react'; import { BrowserRouter, Routes, Route, Link, Outlet } from 'react-router-dom'; // ... (Dashboard, Profile, Settings components) const DashboardHome = () => <h3>欢迎来到仪表盘</h3>; const App = () => { return ( <BrowserRouter> <Routes> {/* 父路由,包含默认子路由 */} <Route path="dashboard" element={<Dashboard />}> <Route index element={<DashboardHome />} /> {/* 默认路由 */} <Route path="profile" element={<Profile />} /> <Route path="settings" element={<Settings />} /> </Route> </Routes> </BrowserRouter> ); }; export default App;
React Router 的嵌套路由是构建复杂 UI 的关键功能,它允许将应用拆分成更小、更易于管理的组件,同时保持导航的简洁和动态性。 通过
以上就是掌握 React Router 中的嵌套路由:构建动态布局的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号