fix: dropdown menu not opening on avatar click

React synthetic event stopPropagation doesn't stop native document
listeners (React 17+ attaches to root, document listener is separate).
The document click handler was closing the menu right after avatar
opened it. Now it checks if the click target is inside the dropdown
or on the avatar and skips closing.
This commit is contained in:
lezi-fun committed 2026-08-10 14:38:30 +08:00
1 parent 2a508d1b21
commit c171efc1ec
5 files changed
+38 -9

No files matched your search

+8 -2
View File
@@ -16,9 +16,15 @@ export default function Navbar({ onOpenModal }) {
API.getCustomPages().then(setCustomPages).catch(() => {});
}, []);
// 点击菜单外部关闭下拉(与原版行为一致)
// 点击菜单外部关闭下拉(检查目标是否在菜单/头像内,避免 React 合成事件与原生监听冲突)
useEffect(() => {
const closeMenu = () => setMenuOpen(false);
const closeMenu = (e) => {
const menu = document.getElementById('userDropdown');
const avatarEl = document.getElementById('userDropdown')?.querySelector('.avatar');
if (menu && menu.contains(e.target)) return;
if (avatarEl && avatarEl.contains(e.target)) return;
setMenuOpen(false);
};
document.addEventListener('click', closeMenu);
return () => document.removeEventListener('click', closeMenu);
}, []);