React页面中点击侧边栏Menu切换渲染对应组件的实现方法
实现侧边栏菜单切换主体组件的方案
1. 基于路由的方案(推荐,支持URL同步)
这种方案会同步URL状态,刷新页面或分享链接时能保留当前页面,适合大多数场景。
第一步:配置根路由
在项目的根路由文件(比如App.js)中,用react-router-dom搭建嵌套路由结构:
import { BrowserRouter, Routes, Route } from 'react-router-dom'; import MainLayout from './path/to/MainLayout'; // 导入你封装好的页面组件 import RicePage from './path/to/RicePage'; import ABTestPage from './path/to/ABTestPage'; function App() { return ( <BrowserRouter> <Routes> {/* 将MainLayout作为父路由容器 */} <Route path="/" element={<MainLayout />}> {/* 默认访问根路径时渲染RicePage */} <Route index element={<RicePage />} /> <Route path="rice" element={<RicePage />} /> <Route path="ab" element={<ABTestPage />} /> </Route> </Routes> </BrowserRouter> ); } export default App;
第二步:修改MainLayout组件
在你的MainLayout中,通过Outlet渲染子路由内容,并同步菜单选中状态:
import { Layout, Menu, theme } from 'antd'; import { useNavigate, useLocation, Outlet } from 'react-router-dom'; const { Sider, Content } = Layout; const items2 = [ { label: 'Rice', key: 'rice' }, { label: 'AB Test', key: 'ab' }, ]; const MainLayout = () => { const { token: { colorBgContainer } } = theme.useToken(); const navigate = useNavigate(); const location = useLocation(); // 根据当前路由路径计算选中的菜单key const currentKey = location.pathname.replace('/', '') || 'rice'; const onClick = (e) => { navigate(`/${e.key}`); }; return ( <Layout style={{ height: '100vh' }}> <Sider width={200} style={{ background: colorBgContainer }}> <Menu mode="inline" items={items2} onClick={onClick} selectedKeys={[currentKey]} // 自动匹配当前路由的选中项 /> </Sider> <Content style={{ padding: '0 24px', minHeight: 280 }}> {/* 这里会渲染匹配到的子路由组件 */} <Outlet /> </Content> </Layout> ); }; export default MainLayout;
2. 基于状态的方案(无需路由,纯组件切换)
如果不需要URL同步,只是在当前页面内切换组件,可以用状态管理实现:
import { Layout, Menu, theme } from 'antd'; import { useState } from 'react'; import RicePage from './path/to/RicePage'; import ABTestPage from './path/to/ABTestPage'; const { Sider, Content } = Layout; const items2 = [ { label: 'Rice', key: 'rice' }, { label: 'AB Test', key: 'ab' }, ]; // 建立菜单key与组件的映射 const pageComponentMap = { rice: <RicePage />, ab: <ABTestPage />, }; const MainLayout = () => { const { token: { colorBgContainer } } = theme.useToken(); const [currentPageKey, setCurrentPageKey] = useState('rice'); // 默认选中Rice页面 const onClick = (e) => { setCurrentPageKey(e.key); }; return ( <Layout style={{ height: '100vh' }}> <Sider width={200} style={{ background: colorBgContainer }}> <Menu mode="inline" items={items2} onClick={onClick} selectedKeys={[currentPageKey]} /> </Sider> <Content style={{ padding: '0 24px', minHeight: 280 }}> {/* 根据选中的key渲染对应组件 */} {pageComponentMap[currentPageKey]} </Content> </Layout> ); }; export default MainLayout;
方案选择
- 需要URL同步(刷新/分享链接保留页面):选路由方案
- 仅需纯组件切换,不需要URL变化:选状态方案
内容的提问来源于stack exchange,提问作者Ahmed Nizami
相关产品推荐
相关产品推荐

