导航抽屉(Navigation Drawer)是一种常见的用户界面组件,通常用于移动应用和桌面应用中,用于展示应用的导航菜单。它通常位于屏幕的左侧或右侧,可以通过滑动或点击图标来打开。
以下是一个使用React和Material-UI实现导航抽屉并在标题中显示当前目标名称的示例代码:
import React, { useState } from 'react';
import { Drawer, List, ListItem, ListItemText, Typography, AppBar, Toolbar, IconButton } from '@material-ui/core';
import { Menu as MenuIcon } from '@material-ui/icons';
const drawerWidth = 240;
function App() {
const [open, setOpen] = useState(false);
const [currentTab, setCurrentTab] = useState('Home');
const handleDrawerOpen = () => {
setOpen(true);
};
const handleDrawerClose = () => {
setOpen(false);
};
const handleTabChange = (tab) => {
setCurrentTab(tab);
};
return (
<div>
<AppBar position="static">
<Toolbar>
<IconButton edge="start" color="inherit" aria-label="menu" onClick={handleDrawerOpen}>
<MenuIcon />
</IconButton>
<Typography variant="h6" style={{ flexGrow: 1 }}>
{currentTab}
</Typography>
</Toolbar>
</AppBar>
<Drawer
variant="persistent"
anchor="left"
open={open}
onClose={handleDrawerClose}
classes={{
paper: 'drawer-paper',
}}
>
<List>
{['Home', 'Profile', 'Settings'].map((text) => (
<ListItem button key={text} onClick={() => handleTabChange(text)}>
<ListItemText primary={text} />
</ListItem>
))}
</List>
</Drawer>
<main style={{ marginLeft: drawerWidth, padding: 24 }}>
{/* Content for the current tab */}
<Typography paragraph>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</Typography>
</main>
</div>
);
}
export default App;
open
状态正确更新。currentTab
状态在点击导航项时正确更新。handleTabChange
函数是否正确调用。通过以上方法,你可以实现一个带有当前目标名称的导航抽屉,并解决常见的实现问题。
领取专属 10元无门槛券
手把手带您无忧上云