react long press event

前端 未结 9 1181
一个人的身影
一个人的身影 2020-12-13 02:01

Is there a way to add long press event in react-web application?

I have list of addresses. On long press on any address, I want to

9条回答
  •  误落风尘
    2020-12-13 02:46

    Nice hook! But I would like make a small improvement. Using useCallback to wrap event handlers. This ensures these will not changed on every render.

    import { useState, useEffect, useCallback } from 'react';
    
    export default function useLongPress(callback = () => {}, ms = 300) {
      const [startLongPress, setStartLongPress] = useState(false);
    
      useEffect(() => {
        let timerId;
        if (startLongPress) {
          timerId = setTimeout(callback, ms);
        } else {
          clearTimeout(timerId);
        }
    
        return () => {
          clearTimeout(timerId);
        };
      }, [callback, ms, startLongPress]);
    
      const start = useCallback(() => {
        setStartLongPress(true);
      }, []);
      const stop = useCallback(() => {
        setStartLongPress(false);
      }, []);
    
      return {
        onMouseDown: start,
        onMouseUp: stop,
        onMouseLeave: stop,
        onTouchStart: start,
        onTouchEnd: stop,
      };
    }
    

提交回复
热议问题