Skip to content

useKey

作用

键盘按键触发

使用

ts
useKey('Enter', () => {
  console.log('Enter key pressed!')
})

源码

ts
import { DependencyList, useMemo } from 'react'
import useEvent, { UseEventOptions, UseEventTarget } from './useEvent'
import { noop } from './misc/util'

export type KeyPredicate = (event: KeyboardEvent) => boolean
export type KeyFilter = null | undefined | string | ((event: KeyboardEvent) => boolean)
export type Handler = (event: KeyboardEvent) => void

//  键盘事件的类型配置
export interface UseKeyOptions<T extends UseEventTarget> {
  event?: 'keydown' | 'keypress' | 'keyup'
  target?: T | null
  options?: UseEventOptions<T>
}

// 判断是不是按键key
const createKeyPredicate = (keyFilter: KeyFilter): KeyPredicate =>
  typeof keyFilter === 'function'
    ? keyFilter
    : typeof keyFilter === 'string'
    ? (event: KeyboardEvent) => event.key === keyFilter
    : keyFilter
    ? () => true
    : () => false

const useKey = <T extends UseEventTarget>(
  // 按键名
  key: KeyFilter,
  // 触发按键执行方法
  fn: Handler = noop,
  // 额外配置
  opts: UseKeyOptions<T> = {},
  // 依赖
  deps: DependencyList = [key]
) => {
  const { event = 'keydown', target, options } = opts
  const useMemoHandler = useMemo(() => {
    const predicate: KeyPredicate = createKeyPredicate(key)
    const handler: Handler = (handlerEvent) => {
      if (predicate(handlerEvent)) {
        return fn(handlerEvent)
      }
    }
    return handler
  }, deps)
  useEvent(event, useMemoHandler, target, options)
}

export default useKey

如有转载或 CV 的请标注本站原文地址