1.0.1 • Published 2 years ago

@hooooks/use-event-listener v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

@hooooks/use-event-listener

A custom React Hook that provides a declarative useEventListener with native event binding.

原生事件绑定hook

Installation

$ npm i @hooooks/use-event-listener

or

$ yarn add @hooooks/use-event-listener

Usage

Here is a basic setup.

useEventListener(element, eventName, handler, options);

Example

import { useRef } from 'react'
import useEventListener from '@hooooks/use-event-listener'

function App ({ children }) {
  const containerRef = useRef<HTMLElement>()
  const scrollContentRef = useRef<HTMLElement>()

  useEventListener(window, 'resize', () => {
    console.log('resize')
  })

  useEventListener(document, 'visibilityChange', hidden => {
    console.log('hidden', hidden)
  }, false)

  // Component Ref
  useEventListener(containerRef, 'contextmenu', () => {
    console.log('contextmenu')
  })

 // native event binding
  useEventListener(scrollContentRef, 'scroll', () => {
    // handle scroll
    console.log('scroll')
  }, {
    passive: true
  })

  return (
    <Container ref={containerRef}>
      <div className='content' ref={scrollContentRef}>
        {children}
      </div>
    </Container>
  )
}

Parameters

Here are the parameters that you can use. (* = optional)

ParameterDescription
elementThe element Window \| Document \| HTMLElement \| Ref<HTMLElement \| ReactInstance> to listen on.
eventNameThe event name (string). Here is a list of common events.
handlerA function that will be called whenever eventName fires on .
options*An object { capture?: boolean, passive?: boolean, once?: boolean } or boolean to be passed to addEventListener. Defaults to false For advanced use cases. See MDN for details.

License

MIT Licensed