在 React 中实现组合键可以使用以下方式:
- 使用 KeyboardEvent.getModifierState() 方法:
import React, { useState, useCallback } from 'react';const MyComponent = () => {const [isCtrlShiftPressed, setIsCtrlShiftPressed] = useState(false);const handleKeyDown = useCallback((event) => {if (event.getModifierState('Control') && event.getModifierState('Shift')) {setIsCtrlShiftPressed(true);}}, []);const handleKeyUp = useCallback((event) => {if (!event.getModifierState('Control') || !event.getModifierState('Shift')) {setIsCtrlShiftPressed(false);}}, []);return (<divonKeyDown={handleKeyDown}onKeyUp={handleKeyUp}tabIndex={0} // 需要给组件一个 tabIndex 属性来使其可以接收键盘事件>{isCtrlShiftPressed ? 'Ctrl + Shift is pressed' : 'Ctrl + Shift is not pressed'}</div>);
};export default MyComponent;
- 使用 Mousetrap 库:
import React, { useEffect } from 'react';
import Mousetrap from 'mousetrap';const MyComponent = () => {useEffect(() => {Mousetrap.bind('ctrl+shift+a', () => {console.log('Ctrl + Shift + A pressed');});return () => {Mousetrap.unbind('ctrl+shift+a');};}, []);return (<div><p>Press Ctrl + Shift + A</p></div>);
};export default MyComponent;
- 使用 ref 和原生事件处理:
import React, { useRef, useCallback } from 'react';const MyComponent = () => {const divRef = useRef(null);const handleKeyDown = useCallback((event) => {if (event.ctrlKey && event.shiftKey && event.key === 'a') {console.log('Ctrl + Shift + A pressed');}}, []);return (<divref={divRef}onKeyDown={handleKeyDown}tabIndex={0} // 需要给组件一个 tabIndex 属性来使其可以接收键盘事件><p>Press Ctrl + Shift + A</p></div>);
};export default MyComponent;