Skip to content

useKeyPress

用于监听键盘事件的hooks。

基础用法

tsx
import { useKeyPress } from 'ono-react-element';

function App() {
    useKeyPress(
        'a',
        (e, key) => {
            console.log(e, key)
        }
    )
}

监听多个按键

tsx
import { useKeyPress } from 'ono-react-element';

function App() {
    useKeyPress(
        ['a', 'b', 'c'],
        (e, key) => {
            console.log(e, key)
        }
    )
}

监听组合键

tsx
import { useKeyPress } from 'ono-react-element';

function App() {
    useKeyPress(
        'Ctrl+a',
        (e, key) => {
            console.log(e, key)
        }
    )
}

精确匹配

tsx
import { useKeyPress } from 'ono-react-element';

function App() {
    useKeyPress(
        'CommandOrControl+a', // 如果想兼容Mac,请使用 CommandOrControl
        (e, key) => {
            console.log(e, key)
        }
    )

    useKeyPress(
        'a',
        (e, key) => {
            console.log(e, key)
        },
        { exactMatch: true } // exactMatch为true时,组合键即便有a键也不会触发
    )
}

API

通用属性参考:通用属性

参数说明类型默认值是否必填
keyFilter支持 keyCode、别名、组合键、数组、自定义函数string|number|FunctionKey-
eventHandler事件处理函数(e: KeyboardEvent, key: string) => void-
options可选配置项Options-

FunctionKey

参数说明
Ctrl控制键
ShiftShift键
AltAlt键
MetaMeta键
CommandOrControlMac下为Command键,Windows下为Control键

Options

参数说明类型默认值是否必填
event触发事件类型keydown|keyupkeydown
target触发事件的目标元素Elementdocument.body
deps依赖项,当依赖项发生变化时,会重新执行监听DependencyList-
exactMatch是否精确匹配组合键booleanfalse