react实现热键
React 实现热键的方法
使用 react-hotkeys-hook 库
安装依赖:
npm install react-hotkeys-hook
基本用法:
import { useHotkeys } from 'react-hotkeys-hook';
function MyComponent() {
useHotkeys('ctrl+s', () => {
console.log('Ctrl+S pressed');
});
return <div>Press Ctrl+S</div>;
}
支持组合键:
useHotkeys('shift+a, shift+b', () => {
alert('Shift+A or Shift+B pressed');
});
原生事件监听
通过 useEffect 和原生键盘事件实现:
import { useEffect } from 'react';
function HotkeyHandler() {
useEffect(() => {
const handleKeyDown = (e) => {
if (e.ctrlKey && e.key === 's') {
e.preventDefault();
console.log('Ctrl+S pressed');
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, []);
return null;
}
使用 react-shortcuts 库
安装:
npm install react-shortcuts
组件式声明:
import { Shortcuts } from 'react-shortcuts';
function MyComponent() {
const handleShortcuts = (action) => {
switch (action) {
case 'SAVE':
console.log('Save action triggered');
break;
}
};
return (
<Shortcuts
name="GLOBAL"
handler={handleShortcuts}
shortcuts={{
SAVE: 'ctrl+s',
}}
/>
);
}
热键作用域控制
react-hotkeys-hook 支持作用域隔离:
useHotkeys('ctrl+s', () => {
// 仅当焦点在指定元素时触发
}, { enableOnTags: ['INPUT'] });
自定义 Hook 封装
创建可复用的热键 Hook:
function useCustomHotkey(key, callback, dependencies = []) {
useEffect(() => {
const handler = (e) => {
if (e.key === key && e.ctrlKey) {
callback();
}
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, dependencies);
}
// 使用示例
useCustomHotkey('s', () => {
alert('Ctrl+S pressed');
});
注意事项
- 阻止浏览器默认行为时需调用
e.preventDefault() - 生产环境应考虑热键冲突问题
- 移动端需额外处理触摸事件
- 复杂组合键建议使用第三方库简化实现
性能优化
对于高频触发的热键:

useHotkeys('*', (e) => {
if (e.key === 'ArrowDown') {
// 节流处理
}
}, { throttle: 300 });






