Material UI导航栏实现点击图标展开不可点击通知列表
实现Material UI导航栏点击图标展开不可点击的通知列表
核心修改思路
- 移除默认带点击交互的
MenuItem,改用非交互组件(如Box、Typography)构建通知项 - 保留原有的Menu展开/关闭状态逻辑,仅替换内部内容结构
- 添加样式优化让列表更贴合通知场景(如分隔线、标题、滚动容器)
修改后的完整代码
import React from 'react'; import { IconButton, Menu, Avatar, Box, Typography, Divider, deepOrange } from '@mui/material'; import NotificationsIcon from '@mui/icons-material/Notifications'; // 模拟通知数据,实际可替换为接口返回内容 const notifications = [ { id: 1, title: '新消息提醒', content: '您收到一条未读私信' }, { id: 2, title: '系统通知', content: '账户安全验证已完成' }, { id: 3, title: '日程提醒', content: '明天14:00有项目评审会议' } ]; export default function NavbarNotifications() { const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null); const user = { displayName: 'sandycheeks' }; // 示例用户信息 const handleMenu = (event: React.MouseEvent<HTMLElement>) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; return ( <div className="nav-links"> <IconButton size="large" aria-label="查看通知" aria-controls="notification-menu" aria-haspopup="true" onClick={handleMenu} color="inherit" > {/* 替换为通知图标,也可保留原头像按需选择 */} <NotificationsIcon /> {/* <Avatar sx={{ bgcolor: deepOrange[500] }}>{user.displayName.charAt(0).toUpperCase()}</Avatar> */} </IconButton> <Menu id="notification-menu" anchorEl={anchorEl} anchorOrigin={{ vertical: 'bottom', horizontal: 'right', }} transformOrigin={{ vertical: 'top', horizontal: 'right', }} open={Boolean(anchorEl)} onClose={handleClose} sx={{ '& .MuiPaper-root': { width: 320, maxHeight: 400, overflowY: 'auto' } }} > {/* 通知列表标题栏 */} <Box sx={{ p: 2, borderBottom: 1, borderColor: 'divider' }}> <Typography variant="h6">通知中心</Typography> </Box> {/* 渲染通知项 */} {notifications.map(notification => ( <React.Fragment key={notification.id}> <Box sx={{ p: 2, cursor: 'default' }}> <Typography variant="subtitle1" fontWeight="bold"> {notification.title} </Typography> <Typography variant="body2" color="text.secondary"> {notification.content} </Typography> </Box> <Divider /> </React.Fragment> ))} {/* 空状态提示(可选) */} {notifications.length === 0 && ( <Box sx={{ p: 3, textAlign: 'center' }}> <Typography variant="body2" color="text.secondary"> 暂无新通知 </Typography> </Box> )} </Menu> </div> ); }
关键细节说明
- 移除交互性:用
Box替代MenuItem,通过cursor: 'default'明确标记不可点击,避免用户误操作 - 定位优化:调整
anchorOrigin和transformOrigin让下拉列表贴合导航栏右侧,符合常规通知栏的布局习惯 - 视觉优化:添加标题栏、分隔线和滚动容器,提升通知列表的可读性和美观度
- 数据适配:通过循环渲染模拟数据,实际项目中可直接替换为后端返回的通知列表数据
内容的提问来源于stack exchange,提问作者sandycheeks
相关产品推荐
相关产品推荐

