[英]close a submenu when another menu item is clicked
I researched and attempted to implement some of the solutions provided, but I was unsuccessful.我研究并尝试实施提供的一些解决方案,但没有成功。 I modified my dropdown menu and click so that each submenu opens and closes when its parent is clicked.
我修改了下拉菜单并单击,以便每个子菜单在单击其父级时打开和关闭。 I'd like to have an open submenu close when a different menu is clicked so that they aren't all stacked at the menu bar.
当单击不同的菜单时,我希望关闭一个打开的子菜单,这样它们就不会全部堆叠在菜单栏上。 Could someone please tell me how I can do this?
有人可以告诉我我该怎么做吗? Thank you for your assistance.
谢谢您的帮助。
I am using next js.我正在使用下一个 js。
<div className={ classNames(classes.root, { [classes.rootActive]: active , [classes.rootExpanded]: isMenuShrunk, })} ref={anchor} onClick={event => handleClick(event, menuItem) } > <button className={classes.menuItemBtn} data-test="menu-item-label" data-test-id={menuItem.testingContextId} > {menuItem.iconSrc && <div className={classNames(classes.icon, { [classes.icon]: isMenuShrunk })} > <SVG src={menuItem.iconSrc}/></div>} <Typography aria-label={menuItem.ariaLabel} className={classNames(classes.label, { [classes.hideLabel]: !isMenuShrunk })} variant="body2" > {menuItem.label} </Typography> </button> {menuItem.children && ( <Collapse timeout="auto" unmountOnExit className={classNames({[classes.popper]: open && isMenuShrunk,})} in={open} > <div> {menuItem.children.map(subMenuItem => ( <Typography aria-label={subMenuItem.ariaLabel} component="button" className={classNames({[classes.subColor]:!color , [classes.subMenuLabel]:open||!open, [classes.sublabel]:open||!open})} key={subMenuItem.url} onClick={event => handleClickSubMenu(event, subMenuItem)} data-test="submenu-item-label" data-test-id={subMenuItem.testingContextId} variant="body2" > {subMenuItem.label} </Typography> ))} </div> </Collapse> )} </div>
Possible solutions可能的解决方案
First第一的
make your open
state a string instead of a boolean move it to the root level and store the opened menu id
in it and also change the open condition like this open==='menuId'
this will enable you to show only one opened menu at a time使您的
open
状态为字符串而不是布尔值,将其移动到根级别并将打开的menu id
存储在其中,并像这样更改打开条件open==='menuId'
这将使您仅显示一个打开的菜单一次
Second第二
Use context API to wrap the whole menu in it and control the state from the context.使用上下文 API 将整个菜单包装在其中并从上下文控制状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.