Created
March 8, 2021 07:11
一個十分鐘寫的土砲 hotkey manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
useHotkey(['Meta', 'c'], () => { | |
console.log( `要跑 1`, ) | |
}) | |
useHotkey(['ctrl', 'c'], () => { | |
console.log( `要跑 2`, ) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const useHotkey = (def, fn) => { | |
const target = def.map(d => d.toLowerCase()).join('-') | |
// console.log( `目標字串`, target ) | |
// | |
useEffect(() => { | |
// | |
const handler = evt => { | |
const keys = [] | |
if(evt.metaKey) keys.push('meta') | |
if(evt.ctrlKey) keys.push('ctrl') | |
if(evt.altKey) keys.push('alt') | |
keys.push(evt.key.toLowerCase()) | |
// console.log( `最終 keys`, keys ) | |
if(keys.join('-') === target){ | |
console.log( `中了`, keys ) | |
} | |
} | |
document.addEventListener('keydown', handler) | |
console.log( `掛了`, ) | |
return window.removeEventListener('keydown', handler) | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment