假设您知道如何使用 react-router-dom。如果不使用此链接找到一个好的指南。
这是使用带有侧边栏的react路由的示例:
import React, { Component } from 'react';
import { ListItemIcon, ListItemText, Divider, IconButton, MenuList, MenuItem, Drawer } from '@material-ui/core';
import { Link, withRouter } from 'react-router-dom';
import { withStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import routes from '../routes/routes';
export class Sidebar extends Component {
constructor(props) {
super(props);
this.activeRoute = this.activeRoute.bind(this);
}
activeRoute(routeName) {
return this.props.location.pathname.indexOf(routeName) > -1 ? true : false;
}
render() {
const { classes, theme } = this.props;
return (
<div>
<Drawer
variant="permanent"
>
<MenuList>
{routes.map((prop, key) => {
return (
<Link to={prop.path} style={{ textDecoration: 'none' }} key={key}>
<MenuItem selected={this.activeRoute(prop.path)}>
<ListItemIcon>
<prop.icon />
</ListItemIcon>
<ListItemText primary={prop.sidebarName} />
</MenuItem>
</Link>
);
})}
</MenuList>
</Drawer>
</div>
);
}
}
export default withRouter(Sidebar);
你的路由器文件应该是这样的:
import { Home, ContentPaste, Notifications, AccountCircle } from '@material-ui/icons';
import HomePage from '../pages/Home/HomePage';
import ProfilePage from '../pages/Profile/ProfilePage';
const Routes = [
{
path: '/dashboard/home',
sidebarName: 'Home',
navbarName: 'Home',
icon: Home,
component: HomePage
},
{
path: '/dashboard/profile',
sidebarName: 'Profile',
navbarName: 'Profile',
icon: AccountCircle,
component: ProfilePage
}
];
export default Routes;
使用 activeRoute 您可以突出显示当前路线
希望能帮到你