仅在右键单击时触发 Chakra UI 菜单
Trigger Chakra UI menu only on right click
是否可以修改文档中的示例,使菜单在右键单击(上下文菜单)而不是正常单击时触发?
<Menu>
<MenuButton as={Button} rightIcon={<ChevronDownIcon />}>
Actions
</MenuButton>
<MenuList>
<MenuItem>Download</MenuItem>
<MenuItem>Create a Copy</MenuItem>
<MenuItem>Mark as Draft</MenuItem>
<MenuItem>Delete</MenuItem>
<MenuItem>Attend a Workshop</MenuItem>
</MenuList>
</Menu>
如果您正在寻找如何使菜单作为上下文菜单工作,请按以下方法实现:
function ContextMenu() {
const [isOpen, setIsOpen] = useState(false);
return (
<Menu
isOpen={isOpen}
onClose={() => {
setIsOpen(false);
}}
>
<Button
onContextMenu={(e) => {
e.preventDefault();
setIsOpen(true);
const menu = document.querySelector("[role=menu]");
const popper = menu.parentElement;
const x = e.clientX;
const y = e.clientY;
Object.assign(popper.style, {
top: `${y}px`,
left: `${x}px`
});
}}
>
Right click to open
</Button>
<MenuList
onAnimationEnd={(e) => {
const menu = document.querySelector("[role=menu]");
menu.focus();
}}
>
<MenuItem>Download</MenuItem>
<MenuItem>Create a Copy</MenuItem>
<MenuItem>Mark as Draft</MenuItem>
<MenuItem>Delete</MenuItem>
<MenuItem>Attend a Workshop</MenuItem>
</MenuList>
</Menu>
);
}
Essentially, you need to first remove the MenuButton that binds to the default click event and then add in a new button to trigger the context menu.
是否可以修改文档中的示例,使菜单在右键单击(上下文菜单)而不是正常单击时触发?
<Menu>
<MenuButton as={Button} rightIcon={<ChevronDownIcon />}>
Actions
</MenuButton>
<MenuList>
<MenuItem>Download</MenuItem>
<MenuItem>Create a Copy</MenuItem>
<MenuItem>Mark as Draft</MenuItem>
<MenuItem>Delete</MenuItem>
<MenuItem>Attend a Workshop</MenuItem>
</MenuList>
</Menu>
如果您正在寻找如何使菜单作为上下文菜单工作,请按以下方法实现:
function ContextMenu() {
const [isOpen, setIsOpen] = useState(false);
return (
<Menu
isOpen={isOpen}
onClose={() => {
setIsOpen(false);
}}
>
<Button
onContextMenu={(e) => {
e.preventDefault();
setIsOpen(true);
const menu = document.querySelector("[role=menu]");
const popper = menu.parentElement;
const x = e.clientX;
const y = e.clientY;
Object.assign(popper.style, {
top: `${y}px`,
left: `${x}px`
});
}}
>
Right click to open
</Button>
<MenuList
onAnimationEnd={(e) => {
const menu = document.querySelector("[role=menu]");
menu.focus();
}}
>
<MenuItem>Download</MenuItem>
<MenuItem>Create a Copy</MenuItem>
<MenuItem>Mark as Draft</MenuItem>
<MenuItem>Delete</MenuItem>
<MenuItem>Attend a Workshop</MenuItem>
</MenuList>
</Menu>
);
}
Essentially, you need to first remove the MenuButton that binds to the default click event and then add in a new button to trigger the context menu.