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
Property | Description | Type | Default |
---|---|---|---|
keyFilter | Support keyCode、alias、combination keys、array、custom function | KeyType | KeyType[] | (event: KeyboardEvent) => boolean | - |
eventHandler | Callback function | (event: KeyboardEvent, key: KeyType) => void | - |
options | Advanced options | Options | - |
Options
Property | Description | Type | Default |
---|---|---|---|
events | Trigger Events | ('keydown' | 'keyup')[] | ['keydown'] |
target | DOM element or ref | () => Element | Element | MutableRefObject<Element> | - |
exactMatch | Exact match. If set true , the event will only be trigger when the keys match exactly. For example, pressing [shift + c] will not trigger [c] | boolean | false |
useCapture | to block events bubbling | boolean | false |
Remarks
All key alias refer to code
Modifier keys
ctrlaltshiftmeta
ctrlaltshiftmeta