我正在尝试构建一个时髦的用例:
我有一个 HeadlessUI 对话框,在这个对话框中,有一个 HeadlessUI Menu 组件作为嵌套子组件,我想通过键盘快捷键触发菜单
我设法通过以下方式触发了对话框:
// I took the useWindowEvent from the headlessUI code
useWindowEvent("keydown", (event) => {
if (event.key === "p") {
event.preventDefault()
event.stopPropagation()
selectorRef.current?.click()
}
})
在我的菜单组件上:
// My react component forwardRefs to the trigger button
export const ProjectSelector = forwardRef(
... some other component code
<Menu.Button ref={ref} as="div">
... other code
这可以很好地触发菜单,但菜单也有一个搜索栏,所以每当我按下 p 键时,侦听器会再次触发并以编程方式关闭菜单
我查看了 headlessUI 代码,试图理解焦点陷阱代码,但它在我的头上,有没有办法检测父对话框是否有焦点?这样,如果焦点在菜单上,我可以忽略按键:)
解决方法:
在写这个问题时,我偶然发现了一个解决方法......它不是超级漂亮,所以也许有人可以想出一个更好的解决方案:
// I'm pretty sure I'm doing everything wrong in here
// but I couldn't find another way to remotely trigger and keep focus on the menu component
useWindowEvent("keydown", (event) => {
if (
event.key === "p" &&
document.activeElement?.getAttribute("role") !== "menu" &&
document.activeElement?.tagName !== "INPUT"
) {
event.preventDefault()
event.stopPropagation()
selectorRef.current?.click()
}
})