@banzai-inc/react-key-handler

中文文档
1.2.0-beta.6发布于 2024/02/15MITESM + CJS近 30 天下载 1.7万

React component to handle keyboard events

原始使用文档
文档目录15 节
  1. Changes for banzai:
  2. Table of Contents
  3. Installation
  4. Usage
  5. Higher-order Components
  6. Component
  7. Form key handling
  8. Key event names
  9. keyValue , code and keyCode
  10. Development
  11. Setup
  12. Getting started
  13. Tests
  14. Contributing
  15. License

react-key-handler 🔑

npm version License Build Status

React component to handle keyboard events (such as keyup, keydown & keypress).

Changes for banzai:

Updated the peer dependency to support react 17 as we have been running this on react 17 for a while now. This package will eventually need to be replaced with something different as part of our upgrades.

Table of Contents

Installation

$ npm install react-key-handler --save

Usage

You can use react-key-handler library in two flavours:

Higher-order Components

This library includes two similar higher-order components, but with a different puprose:

Higher-order ComponentPurpose
keyHandlerHandles key changes
keyToggleHandlerHandles key toggles

Both have the same API and will decorate the given component with a keyValue, code and keyCode property.

Internally the KeyHandler component is used, for a full understanding be sure to check out the implementation.

import React from 'react';
import { keyHandler, KEYPRESS } from 'react-key-handler';

function Demo({ keyValue }) {
  return (
    <div>
      {keyValue === 's' && (
        <ol>
          <li>hello</li>
          <li>world</li>
        </ol>
      )}
    </div>
  );
}

export default keyHandler({ keyEventName: KEYPRESS, keyValue: 's' })(Demo);

The prop types of the KeyHandler component are:

NameTypeRequiredDefault
keyEventNamestringno'keyup''keydown', 'keypress' or 'keyup'
keyValuestringyes *Any given KeyboardEvent.key
codestringyes *Any given KeyboardEvent.code
keyCode†numberyes *Any given KeyboardEvent.keyCode

* You should pass at least one of these props.

† Note that the keyCode is frequently browser specific and has therefore be set as deprecated, see MDN for details.

Examples

Component

import React from 'react';
import KeyHandler, { KEYPRESS } from 'react-key-handler';

export default class Demo extends React.Component {
  state = { showMenu: false };

  render() {
    const { showMenu } = this.state;

    return (
      <React.Fragment>
        <KeyHandler
          keyEventName={KEYPRESS}
          keyValue="s"
          onKeyHandle={this.toggleMenu}
        />

        {showMenu && (
          <ol>
            <li>hello</li>
            <li>world</li>
          </ol>
        )}
      </React.Fragment>
    );
  },

  toggleMenu = (event) => {
    event.preventDefault();

    this.setState({ showMenu: !this.state.showMenu });
  };
}

The prop types of the KeyHandler component are:

NameTypeRequiredDefault
keyEventNamestringno'keyup''keydown', 'keypress' or 'keyup'
keyValuestringyes *Any given KeyboardEvent.key
codestringyes *Any given KeyboardEvent.code
keyCode†numberyes *Any given KeyboardEvent.keyCode
onKeyHandlefunctionyesFunction that is called when they key is handled

* You should pass at least one of these props.

† Note that the keyCode is frequently browser specific and has therefore be set as deprecated, see MDN for details.

Example

Form key handling

This library does not handle key events for form elements such as <input /> and <textarea />.

React does a fine job supporting these already via keyboard events.

Examples

Key event names

TODO: explain the differences between the different key events.

keyValue, code and keyCode

The three available key events are

  • keyValue This corresponds to the true value. This is the value of the key pressed by the user while taking into considerations the state of modifier keys such as the shiftKey as well as the keyboard locale/layout
  • code This corresponds to the physical key on the keyboard (as opposed to the character generated by pressing the key). In other words, this property returns a value which isn't altered by keyboard layout or the state of the modifier keys. The value is a string specific to the key, e.g. 'Digit0'
  • keyCode This is similar to code but numeric and also deprecated.

We recommend you to use the new Web standard KeyboardEvent.key or the KeyboardEvent.code over the deprecated KeyboardEvent.keyCode.

Note that in React key is a reserved property, and thus we use keyValue when referring to the key property.

Browser support:

There's no need to worry about browser support because internally we normalize deprecated HTML5 keyValue values and translate from legacy keyCode values, similar to how React does this for their SyntheticKeyboardEvent.

More information:

W3C Working Draft.

Development

Setup

$ git clone <this repo>
$ cd react-key-handler
$ npm install

Getting started

To start the server:

$ npm demo

This starts a development server, which will automatically rebuild the demo app as you change files and supports hot module replacement for fast development:

$ open http://localhost:1234

Tests

To run all tests:

$ npm test

Or you can run the linters, unit tests and check for type errors individually:

$ npm run test:lint
$ npm run test:unit
$ npm run test:flow

Contributing

Bug reports and pull requests are welcome on GitHub. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

 _________________
< The MIT License >
 -----------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

版本与发布记录

@banzai-inc/react-key-handler 共发布 4 个版本,首次发布于 2023/05/19;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.2.0-beta.6latest2024/02/152 年前
1.2.0-beta.52024/02/152 年前
1.2.0-beta.42024/02/142 年前
1.2.0-beta.32023/05/193 年前

关于 @banzai-inc/react-key-handler 的常见问题

@banzai-inc/react-key-handler 是什么?

React component to handle keyboard events

如何安装 @banzai-inc/react-key-handler?

在项目目录运行 npm install @banzai-inc/react-key-handler,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^16.2.0-0 || ^17.0.0 || ^18.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@banzai-inc/react-key-handler 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/banzai-inc__react-key-handler 是否存在。

@banzai-inc/react-key-handler 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@banzai-inc/react-key-handler 可以商用吗?

@banzai-inc/react-key-handler 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@banzai-inc/react-key-handler 的下载量有多少?

根据 npm 官方下载统计,@banzai-inc/react-key-handler 在 2026/10/08 – 2026/11/06 这 30 天内被下载 17,315 次,日均约 577 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@banzai-inc/react-key-handler 还在维护吗?

最新版本 1.2.0-beta.6 发布于 2024/02/15(2 年前);至今共发布 4 个版本,其中过去 12 个月发布了 0 个;首次发布于 2023/05/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。