创建一个像这样的钩子。
import React, {useEffect, useState} from "react";
const useKeyPress = (keyMap, callbackMap) => {
const [keyPressed, setKeyPressed] = useState(new Set());
const downHandler = (event) => {
event.preventDefault();
const { key, altKey, shiftKey, ctrlKey } = event;
const modifiers = [];
if (altKey) modifiers.push('alt');
if (shiftKey) modifiers.push('shift');
if (ctrlKey) modifiers.push('ctrl');
const combinations = [ [key.toLowerCase()],
[modifiers.join('+'), key.toLowerCase()],
[modifiers.reverse().join('+'), key.toLowerCase()]
];
for (const combination of combinations) {
const id = keyMap[combination.join('+')];
const callback = callbackMap[id];
if (callback) {
const newKeyPressed = new Set(keyPressed);
newKeyPressed.add(combination.join('+'));
setKeyPressed(newKeyPressed);
callback();
break;
}
}
};
const upHandler = (event) => {
event.preventDefault();
const { key, altKey, shiftKey, ctrlKey } = event;
const modifiers = [];
if (altKey) modifiers.push('alt');
if (shiftKey) modifiers.push('shift');
if (ctrlKey) modifiers.push('ctrl');
const combinations = [ [key.toLowerCase()],
[modifiers.join('+'), key.toLowerCase()],
[modifiers.reverse().join('+'), key.toLowerCase()]
];
for (const combination of combinations) {
const id = keyMap[combination.join('+')];
const callback = callbackMap[id];
if (callback) {
const newKeyPressed = new Set(keyPressed);
newKeyPressed.delete(combination.join('+'));
setKeyPressed(newKeyPressed);
break;
}
}
};
useEffect(() => {
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);
return () => {
window.removeEventListener('keydown', downHandler);
window.removeEventListener('keyup', upHandler);
};
});
return keyPressed;
};
export default useKeyPress;
然后在您的其他组件中可以像这样使用它;
const keyMap = {
'ctrl+shift+p': 'preview',
};
const callbackMap = {
'preview': () => setShowModal(prevModalVisible => !prevModalVisible),
};
useKeyPress(keyMap, callbackMap);
通过技巧,您可以映射任何您喜欢的三个键组合
e.nativeEvent.shiftKey
? - Teemuif
语句内添加console.log(e.nativeEvent.shiftKey);
时,我得到了undefined
。 - Leopold Joy'Shift'
而不是'Enter'
了吗?啊... Shift 没有触发keypress
... - TeemuShift
键和Enter
键是否同时按下,我该怎么做? - Leopold Joykeydown
或keyup
,因为keypress
不会被 SHIFT 触发,尽管.shiftKey
仍然应该被定义。 - Teemukeydown
事件中记录 SHIFT 键被按下,然后在keyup
事件中记录它被松开。然后当按下回车键时,我就可以检查同时是否也按下了 Shift 键。我会尝试这样做的,谢谢! - Leopold Joy