我需要在react应用程序的输入表单中设置按钮组合。
- "CTRL+";向上箭头">
- "向上箭头">
我的代码是这样的
//Form
<input onKeyDown={keyHandler}/>
//handler
const keyhandler = (e) => {
if(e.key === "ArrowUp") {//do something}
if(e.key === 'ArrowUp' && e.getModifierState("Control")) {//do another thing}
问题是当使用组合触发事件时,首先"if"也是true。如何分离";向上箭头";以及";向上箭头";用ctrl按钮?
我也试过这样做(但没有帮助(:
if(e.key === 'ArrowUp' && event.ctrlKey){ //do another thing}
只需遵循您的逻辑,
if (Control is pressed) {
if (ArrowUp is pressed) {
// both are pressed
}
} else {
if (ArrowUp is pressed) {
// only arrow up is pressed
}
}
我用这个解决了我的问题。
if(!e.getModifierState('Control')){
if(e.key == 'ArrowUp'){
//single button action
}
}
if(e.key == "ArrowUp" && e.getModifierState("Control")){
//combo buttons action
}