gpt4 book ai didi

reactjs - React Router v6 useNavigate 与 MUI Drawer

转载 作者:行者123 更新时间:2023-12-05 05:52:23 24 4
gpt4 key购买 nike

在应用程序中使用它之前,我正在使用 stackblitz 尝试实现 MUI Drawer 和 react-router-dom。我认为我没有正确使用 useNavigate Hook ?任何帮助将不胜感激

抽屉.js

const Drawer = () => {
const classes = useStyles();
let navigate = useNavigate();

const itemsList = [
{
text: 'Home',
icon: <InboxIcon />,
onClick: () => navigate('/home'),
},
{
text: 'About',
icon: <MailIcon />,
},
{
text: 'Contact',
icon: <MailIcon />,
},
];
return (
<MUIDrawer variant="permanent" className={classes.drawer}>
<List>
{itemsList.map((item, index) => {
const { text, icon, onClick } = item;
return (
<ListItem button key={text} onClick={onClick}>
{icon && <ListItemIcon>{icon}</ListItemIcon>}
<ListItemText primary={text} />
</ListItem>
);
})}
</List>
</MUIDrawer>
);
};
export default Drawer;

App.js

const App = () => {
const classes = useStyles()
return (
<div className={classes.container}>
<Drawer />
<Router>
<Routes>
<Route path="/" exact element={<Home />} />
<Route path="/contact" element={<Contact />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
</div>
);
};

最佳答案

该错误是由于在 App.js 中将 Drawer 置于 Router 之外。当我复制我应该包含在我的原始帖子中的 useStyles 时,我也犯了一个用户错误。

App.js

const useStyles = makeStyles({
container: {
display: 'flex',
},
});
const App = () => {
const classes = useStyles();
return (
<div className={classes.container}>
<Router>
<Drawer />
<Routes>
<Route path="/home" exact element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Router>
</div>
);
};

抽屉.js

const useStyles = makeStyles({
drawer: {
width: '190px',
},
});

const Drawer = () => {
const classes = useStyles();
let navigate = useNavigate();

const itemsList = [
{
text: 'Home',
icon: <InboxIcon />,
onClick: () => navigate('/home'),
},
{
text: 'About',
icon: <MailIcon />,
onClick: () => navigate('/about'),
},
{
text: 'Contact',
icon: <MailIcon />,
onClick: () => navigate('/contact'),
},
];
return (
<MUIDrawer variant="permanent" className={classes.drawer}>
<List>
{itemsList.map((item, index) => {
const { text, icon, onClick } = item;
return (
<ListItem button key={text} onClick={onClick}>
{icon && <ListItemIcon>{icon}</ListItemIcon>}
<ListItemText primary={text} />
</ListItem>
);
})}
</List>
</MUIDrawer>
);
};

export default Drawer;

关于reactjs - React Router v6 useNavigate 与 MUI Drawer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70163632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com