Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
一個十分鐘寫的土砲 hotkey manager
useHotkey(['Meta', 'c'], () => {
console.log( `要跑 1`, )
})
useHotkey(['ctrl', 'c'], () => {
console.log( `要跑 2`, )
})
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