项目作者: SAITS

项目描述 :
React hook to attach keyboard shortcuts to the document
高级语言: TypeScript
项目地址: git://github.com/SAITS/use-keyboard-shortcuts.git
创建时间: 2019-07-09T13:05:13Z
项目社区:https://github.com/SAITS/use-keyboard-shortcuts

开源协议:

下载


use-keyboard-shortcuts

An intuitive React hook to enable keyboard shortcuts.

NPM JavaScript Style Guide

Quick Example

  1. useKeyboardShortcuts([
  2. { keys: ["ctrl", "a"], onEvent: event => alert("ctrl + a was pressed") },
  3. { keys: ["shift", "b"], onEvent: event => alert("shift + b was pressed") },
  4. { keys: ["Tab"], handleNext },
  5. { keys: ["Esc"], handleClose },
  6. { keys: ["Enter"], handleSubmit, preventDefault: false },
  7. ])
  8. useKeyboardShortcuts(
  9. [{ keys: ["ctrl", "shift"], onEvent: () => alert('ctrl + shift + scroll is active') }],
  10. true,
  11. [],
  12. "mousewheel"
  13. )
  14. }

Features

  • Easy to use
  • Typescript support
  • Multiple shortcuts registered at the same time
  • Support for special keys: Shift, Ctrl (command on Mac), Alt (option on Mac).
  • Support for keydown and mousewheel events
  • Prevents mature propagation. This means that if you have a shortcut for ctrl + a and ctrl + shift + a in the same hook, then the action
    for ctrl + a will not trigger when pressing ctrl + shift + a.

Install

  1. $ npm install --save use-keyboard-shortcuts
  2. $ yarn add use-keyboard-shortcuts

Usage

  1. import React from "react"
  2. import useKeyboardShortcuts from "use-keyboard-shortcuts"
  3. const Example = () => {
  4. const [isOpen, setIsOpen] = React.useState(false)
  5. useKeyboardShortcuts([
  6. { keys: ["ctrl", "a"], onEvent: event => alert("ctrl + a was pressed") },
  7. { keys: ["Esc"], onEvent: () => setIsOpen(false) },
  8. ])
  9. return <div>...</div>
  10. }

Arguments

Argument (in order) Type Default Description
shortcuts Shortcut[] undefined Array of Shortcut-objects that should listen to the specified dependencies and eventType. See Shortcut object-section.
active boolean true Disables or enables all shortcuts.
dependencies any[] [] List dependencies of the shortcuts
eventType "keydown"/"mousewheel" "keydown" Wether it should listen for keyboard or mouse scroll events

Shortcut object

Key Type Description
keys string[] Combination of keys that needs to be pressed to trigger onEvent().
onEvent function(event) Action for when combination in keys are pressed.
disabled boolean Used to disable a shortcut in particular

Example

See the example-folder for an extended example of how to use this hook with the mousewheel event type.

License

MIT � SAITS