要在React中實現(xiàn)右鍵菜單,可以使用onContextMenu
事件來監(jiān)聽鼠標右鍵單擊事件,并根據(jù)需要顯示或隱藏菜單。下面是一個簡單的示例代碼:
import React, { useState } from 'react';
const ContextMenu = () => {
const [showMenu, setShowMenu] = useState(false);
const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });
const handleContextMenu = (e) => {
e.preventDefault();
setShowMenu(true);
setMenuPosition({ x: e.clientX, y: e.clientY });
};
const handleItemClick = () => {
setShowMenu(false);
};
return (
<div onContextMenu={handleContextMenu}>
<div style={{ position: 'relative' }}>
{showMenu && (
<div
style={{
position: 'absolute',
top: menuPosition.y,
left: menuPosition.x,
backgroundColor: '#fff',
border: '1px solid #ccc',
padding: '5px',
}}
>
<div onClick={handleItemClick}>Item 1</div>
<div onClick={handleItemClick}>Item 2</div>
<div onClick={handleItemClick}>Item 3</div>
</div>
)}
</div>
Right click here to open context menu
</div>
);
};
export default ContextMenu;
在上面的代碼中,我們定義了一個ContextMenu
組件,其中監(jiān)聽了onContextMenu
事件。當(dāng)鼠標右鍵單擊時,會顯示一個簡單的菜單,并在點擊菜單項時隱藏菜單。你可以根據(jù)實際需求來自定義菜單的樣式和內(nèi)容。