动态材质 UI 下拉菜单

我正在使用 material-ui js 创建一个动态下拉菜单,但是当我单击其中一个菜单时,它会打开所有菜单,反之亦然。

法典


LEATH
浏览 87回答 1
1回答

九州编程

您正在为两个菜单链接维护 1 个状态。维护列表的名称(页面标题)。在函数中,使用键动态设置/切换状态对象。handlerListOpen您的代码和框的工作副本代码片段:export default function App() {&nbsp; const [openList, setopenList] = React.useState({});&nbsp; const handlerListOpen = el => {&nbsp; &nbsp; console.log("el", el.currentTarget.getAttribute("name"));&nbsp; &nbsp; const target = el.currentTarget;&nbsp; &nbsp; setopenList(prev => ({&nbsp; &nbsp; &nbsp; ...prev,&nbsp; &nbsp; &nbsp; [target.getAttribute("name")]: !prev[&nbsp; &nbsp; &nbsp; &nbsp; target.getAttribute("name")&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }));&nbsp; };&nbsp; return (&nbsp; &nbsp; <List component={"nav"}>&nbsp; &nbsp; &nbsp; {pages.map((page, index) => (&nbsp; &nbsp; &nbsp; &nbsp; <List>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ListItem name={page.title} button onClick={handlerListOpen}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ListItemIcon>{pages.icon}</ListItemIcon>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ListItemText primary={page.title} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {openList[page.title] ? <ExpandLess /> : <ExpandMore />}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </ListItem>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {page.collapse.map((collapse, index) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Collapse in={openList[page.title]} timeout="auto" unmountOnExit>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {" "}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Link to={collapse.href}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <List component="div" disablePadding key={index}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ListItem button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ListItemIcon>{collapse.icon}</ListItemIcon>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ListItemText primary={collapse.title} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ListItemIcon>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ChevronRightIcon />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </ListItemIcon>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </ListItem>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </List>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Link>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Collapse>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; &nbsp; </List>&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; </List>&nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript