[英]On Opening one dropdown the other drop down if it is opened should close
我想添加在打开另一个菜单时自动关闭已经打开的下拉菜单的逻辑。 例如,我打开了功能 1 下拉菜单,当我单击功能 2 打开时,功能 1 下拉菜单应该关闭,反之亦然。
const [expand1, setExpand1] = useState(false);
const [expand2, setExpand2] = useState(false);
<ul>
<li>
<div onClick ={() => setExpand1(!expand1)}>
<a onClick={() => openPane('1')} className="menu-item">
<span>Feature-1</span>
<div className={`drop-down ${expand1 ? 'active' : ""}`}>
<i class='bx bx-chevron-down'></i>
</div>
</a>
</div></li>
<li>
<div onClick ={() => setExpand2(!expand2)}>
<a onClick={() => openPane('2')} className="menu-item">
<span>Feature-2</span>
<div className={`drop-down ${expand2 ? 'active' : ""}`}>
<i class='bx bx-chevron-down'></i>
</div>
</a>
</div>
</li>
</ul>
尝试将自定义函数添加为onClick
处理程序并在那里处理逻辑。
const [expand1, setExpand1] = useState(false);
const [expand2, setExpand2] = useState(false);
const toggle1 = () => {
if(expand2) setExpand2(false)
setExpand1(!expand1)
}
const toggle2 = () => {
if(expand1) setExpand1(false)
setExpand2(!expand2)
}
<ul>
<li>
<div onClick ={toggle1}>
<a onClick={() => openPane('1')} className="menu-item">
<span>Feature-1</span>
<div className={`drop-down ${expand1 ? 'active' : ""}`}>
<i class='bx bx-chevron-down'></i>
</div>
</a>
</div></li>
<li>
<div onClick ={toggle2}>
<a onClick={() => openPane('2')} className="menu-item">
<span>Feature-2</span>
<div className={`drop-down ${expand2 ? 'active' : ""}`}>
<i class='bx bx-chevron-down'></i>
</div>
</a>
</div>
</li>
</ul>
这是非常不干净的,但展示了一般的想法。
您可以通过使用焦点和模糊来实现这一点。 <div>
不会自动获得焦点,因此您需要为其提供tabIndex
属性以使其成为焦点。
<div tabIndex="0">
<p>Hello</p>
</div>
现在, <div>
是可聚焦的。
接下来你需要做的是给<div>
一个onFocus
和onBlur
来隐藏或显示<div>
。
const menuRef = React.useRef()
const [focusedIndex, setFocusedIndex] = React.useState(null)
const onFocus = (e, {index}) => setFocusedIndex(index)
const onBlur = (e, {index}) => {
setFocusedIndex(null)
// you can implement your own logic here
}
return (
<div ref={menuRef}>
{
['a', 'b'].map((val, i) => (
<div
onFocus={(e) => onFocus(e, {index: i})}
onBlur={(e) => onBlur(e,{index: i})}
tabIndex="0"
style={{display: focusedIndex === i ? 'block' : 'none'}}
key={`${i}`}
>
<p>Hello</p>
</div>
)
}
</div>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.