React路由结合Material UI的ListItemButton组件完成导航示例
- 1、创建菜单列表NavigationList.jsx
- 2、App.js
1、创建菜单列表NavigationList.jsx
import React from 'react';
import { ListItemButton, ListItemText, List } from '@mui/material';
import { NavLink as RouterLink } from 'react-router-dom';
const items = [
{ id: 1, path: '/home', label: 'Home' },
{ id: 2, path: '/about', label: 'About' },
];
const NavigationList = () => {
return (
<div>
<List>
{items.map((item) => (
<ListItemButton
key={item.id}
component={RouterLink}
to={item.path}
>
<ListItemText primary={item.label} />
</ListItemButton>
))}
</List>
</div>
);
};
export default NavigationList;
export default NavigationList;
提示:以下是本篇文章正文内容,下面案例可供参考
2、App.js
import {BrowserRouter, Route, Routes} from "react-router-dom";
import NavigationList from "./NavigationList";
import HomePage from "./Home";
import AboutPage from "./About";
function App() {
return (
<BrowserRouter>
<NavigationList />
<Routes>
<Route path="/home" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
{/* 可以添加更多路由... */}
<Route path="/" element={<HomePage />} /> {/* 默认路由 */}
</Routes>
</BrowserRouter>
);
}
export default App;
这篇文章主要记录我对ListItemButton的认知。下图默认重定向到HomePage页面。点击Home和About文字可以切换
切换About
当然NavigationList.jsx中的代码也可以如下写法:
import React from 'react';
import {List, ListItemButton, ListItemText} from '@mui/material';
import {NavLink} from "react-router-dom";
const items = [
{ id: 1, path: '/home', label: 'Home' },
{ id: 2, path: '/about', label: 'About' },
];
const NavigationList = () => {
return (
<div>
<List>
{items.map((item) => (
<li key={item.id}>
<NavLink to={item.path}>
<ListItemButton>
<ListItemText primary={item.label} />
</ListItemButton>
</NavLink>
</li>
))}
</List>
</div>
);
};
export default NavigationList;
- 注意,这里我们没有使用ListItemButton的component属性来包装NavLink,而是直接让NavLink作为最外层的元素,并将ListItemButton和ListItemText作为其子元素。这样做可以确保NavLink负责处理路由的导航,而ListItemButton只负责提供样式和交互。