reactjs 如何只有一个活动状态显示下拉菜单和其他错误的React

v8wbuo2f  于 2023-02-18  发布在  React
关注(0)|答案(2)|浏览(125)

我正在尝试做一个下拉式导航。这个想法是只有一个活动的下拉式导航时,点击和其他关闭。目前它的工作原理如下,我有,但我目前卡住的地方,两个下拉式是在同一时间打开时,都被点击。
我如何切换/添加只有一个活动状态,并把其他的单独功能状态为假?请帮助..

export default function Header(args) {
    const [isActive, setActive] = useState(false);
    const [isResourceActive, setResourceActive] = useState(false);
        
    const handleToggle = () => {setActive(!isActive);};
    const resourcesHandleToggle = () => {setResourceActive(!isResourceActive);};

         return (
    <NavItem onClick={handleToggle} className={isActive ? "active" : ""}></NavItem>  
    <NavItem onClick={resourcesHandleToggle} className={isResourceActive ? "active" :""}</NavItem>
        
        
        <div className={isActive ? "active": ""}>DROPDOWN_1</div>
        <div className={isResourceActive ?"active": ""}>DROPDOWN_2</div>
    )
pgccezyw

pgccezyw1#

const [active, setActive] = useState(undefined);
const toggle = (name) => {
  if (active === name) {
    setActive(undefined)
  } else {
    setActive(name)
  }
}
<NavItem onClick={() => toggle('DROPDOWN_1')} className={active === 'DROPDOWN_1' ? "active" : ""}></NavItem>  
<NavItem onClick={() => toggle('DROPDOWN_2')} className={active === 'DROPDOWN_2' ? "active" :""}</NavItem>
<div className={active === 'DROPDOWN_1' ? "active": ""}>DROPDOWN_1</div>
<div className={active === 'DROPDOWN_2' ? "active": ""}>DROPDOWN_2</div>
mwkjh3gx

mwkjh3gx2#

只强制其他dropp为false(或者如果你想的话先用“if”检查它)

const handleToggle = () => {    
    setActive(!isActive);
    setResourceActive(false);    
};
   

 const resourcesHandleToggle = () => {
    setResourceActive(!isResourceActive);
    setActive(false);    
};

相关问题