跳转到内容

useKeyPress

检测键盘按键,支持可选的回调。

import { useKeyPress, useKeyPressCallback } from 'asterui'
function KeyPressExample() {
const escapePressed = useKeyPress('Escape')
useEffect(() => {
if (escapePressed) closeModal()
}, [escapePressed])
return <div>{escapePressed ? 'Escape pressed!' : 'Press Escape'}</div>
}
function CallbackExample() {
useKeyPressCallback('Escape', () => closeModal())
useKeyPressCallback('Enter', () => submitForm(), { preventDefault: true })
return <Form>...</Form>
}
参数类型描述
targetKeystring要检测的键(例如 'Enter''Escape''a'
optionsUseKeyPressOptions配置选项
参数类型描述
targetKeystring要检测的键
callback(event: KeyboardEvent) => void要调用的函数
optionsUseKeyPressOptions配置选项
属性类型默认值描述
targetHTMLElement | Windowwindow监听器的目标元素
event'keydown' | 'keyup''keydown'要监听的事件类型
preventDefaultbooleanfalse阻止默认浏览器行为
类型描述
boolean按键被按下时为 true