useKeyPress

Listen for the keyboard press, support key combinations, and support alias.

Examples

Basic usage

Try pressing the following:

1. Press ArrowUp by key to increase
2. Press ArrowDown by keyCode to decrease
counter: 0

Basic usage

Supported keyCode and alias in keyboard events, pressing ArrowUp or ArrowDown to show effect.

Combination keys

Try pressing the following:

1. Modifier key [shift.c]:
2. Modifier key [meta]:
3. Modifier key [ctrl.alt.c]:
4. Modifier key [ctrl.enter]:
5. Modifier key [ctrl.alt.0]:

Exact match

Multiple keys

Try pressing the following:

1. Number key [0-9]:
2. Press key [a, s, d, f, Backspace, 8]:

Get the trigger key

Try pressing the following:

1. Press [w] to increase
2. Press [s] to decrease
3. Press [shift.c] to reset

counter: 0

Get the trigger key

Multiple shortcuts are registered by a hook, each corresponding to a different logic.

Custom method

Pressing key except number key:

Advanced

Supports receiving a Boolean callback function to handle preprocessing operations.

Custom DOM

Input and pressing enter:

Input and pressing enter:

Input after enter change:

Custom DOM

By default, listen for events on the window. You can also pass in a DOM to set listen area. such as the common listening for input box events.

API

type KeyType = number | string;type KeyFilter = KeyType | KeyType[] | ((event: KeyboardEvent) => boolean);useKeyPress(  keyFilter: KeyFilter,  eventHandler: (event: KeyboardEvent, key: KeyType) => void,  options?: Options);
type KeyType = number | string;type KeyFilter = KeyType | KeyType[] | ((event: KeyboardEvent) => boolean);useKeyPress(  keyFilter: KeyFilter,  eventHandler: (event: KeyboardEvent, key: KeyType) => void,  options?: Options);

Params

PropertyDescriptionTypeDefault
keyFilterSupport keyCode、alias、combination keys、array、custom functionKeyType | KeyType[] | (event: KeyboardEvent) => boolean-
eventHandlerCallback function(event: KeyboardEvent, key: KeyType) => void-
optionsAdvanced optionsOptions-

Options

PropertyDescriptionTypeDefault
eventsTrigger Events('keydown' | 'keyup')[]['keydown']
targetDOM element or ref() => Element | Element | MutableRefObject<Element>-
exactMatchExact match. If set true, the event will only be trigger when the keys match exactly. For example, pressing [shift + c] will not trigger [c]booleanfalse
useCaptureto block events bubblingbooleanfalse

Remarks

  1. All key alias refer to code

  2. Modifier keys

ctrlaltshiftmeta
ctrlaltshiftmeta