react long press event

前端 未结 9 1191
一个人的身影
一个人的身影 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:39

    With hooks in react 16.8 you could rewrite class with functions and hooks.

    import { useState, useEffect } 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]);
    
      return {
        onMouseDown: () => setStartLongPress(true),
        onMouseUp: () => setStartLongPress(false),
        onMouseLeave: () => setStartLongPress(false),
        onTouchStart: () => setStartLongPress(true),
        onTouchEnd: () => setStartLongPress(false),
      };
    }
    
    import useLongPress from './useLongPress';
    
    function MyComponent (props) {
      const backspaceLongPress = useLongPress(props.longPressBackspaceCallback, 500);
    
      return (
        
          
        
      );
    };
    
    

提交回复
热议问题