我正在尝试使用Material UI React抽屉,但对如何实现选择感到困惑,以便对组件进行更改。例如,我有一个名为Get Videos的选择,它应该调用我的组件,该组件对S3执行AXIOS调用以获取存储桶中的文件。
如何在我的选择中切换组件?我应该使用路线还是应该将组件的状态设置为"活动"?任何帮助将不胜感激..
一些代码
handleClick(event) {
????
}
render() {
return (
<div>
<ListItem button>
<ListItemIcon>
<ScheduleIcon/>
</ListItemIcon>
<ListItemText primary="Scheduler" onClick={this.handleClick.bind(this)}/>
</ListItem>
<ListItem button onClick={this.handleClick()}>
<ListItemIcon>
<ViewListIcon/>
</ListItemIcon>
<ListItemText primary="Watch Saved Recordings"/>
</ListItem>
</div>
);
}
答案 0 :(得分:4)
假设您知道如何使用react-router-dom。如果不使用this链接找到一个好的指南。
以下是使用侧边栏进行反应路由的示例:
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,您可以突出显示当前路线
希望这会对你有所帮助
答案 1 :(得分:1)
此外,您可以使用useLocation使用钩子
import { useLocation } from "react-router-dom";
然后您可以创建相同的行为
const [path, setPath] = useState("");
let location = useLocation();
useEffect(() => {
setPath(location.pathname);
console.log(location.pathname)
}, [location,setPath]);
const activetRoute = route => {
console.log(route , path);
return route === path;
}
和
<List>
{routers.map((item, key) => (
<ListItem
key={key}
button
component={Link}
to={item.path}
selected={activetRoute(item.path)}
>
<ListItemIcon>
<item.icon />
</ListItemIcon>
<ListItemText primary={item.sidebarName} />
</ListItem>
))}
</List>