React Hooks TS 长按点击事件

当前需要事件文件夹下创建 LongPress.tsx 文件;

import { useCallback, useRef, useState } from "react";

/**
 * 
 * @param onLongPress 长按事件
 * @param onClick 点击事件
 * @param stopLongPress 长按事件结束状态
 * @param param2 
 * @returns 
 */

const useLongPress = (
    onLongPress: (arg0: any) => void,
    onClick: () => any,
    stopLongPress: () => any,
    { shouldPreventDefault = true, delay = 300 } = {}
) => {
    const [longPressTriggered, setLongPressTriggered] = useState(false);
    const timeout: any = useRef();
    const target: any = useRef();

    const start = useCallback(
        event => {
            if (shouldPreventDefault && event.target) {
                event.target.addEventListener("touchend", preventDefault, {
                    passive: false
                });
                target.current = event.target;
            }
            timeout.current = setTimeout(() => {
                onLongPress(event);
                setLongPressTriggered(true);
            }, delay);
        },
        [onLongPress, delay, shouldPreventDefault]
    );

    const clear = useCallback(
        (event, shouldTriggerClick = true) => {
            timeout.current && clearTimeout(timeout.current);
            shouldTriggerClick && !longPressTriggered && onClick();
            if (longPressTriggered) {
                stopLongPress()
            }
            setLongPressTriggered(false);

            if (shouldPreventDefault && target.current) {
                target.current.removeEventListener("touchend", preventDefault);
            }
        },
        [shouldPreventDefault, onClick, longPressTriggered, stopLongPress]
    );

    return {
        onTouchStart: (e: any) => start(e),
        onTouchEnd: (e: any) => clear(e)
    };
};

const isTouchEvent = (event: any) => {
    return "touches" in event;
};

const preventDefault = (event: { touches: string | any[]; preventDefault: () => void; }) => {
    if (!isTouchEvent(event)) return;

    if (event.touches.length < 2 && event.preventDefault) {
        event.preventDefault();
    }
};

export default useLongPress;

  在需要的文件中引用 

import useLongPress from "../LongPress";

  使用时

const IOTDoubleButton = () => {
 
 const longPressHandler = useLongPress(() => {console.log('长按事件') }, () => { console.log('点击事件') }, ()=>{console.log('结束长按事件')});

 return (
   <div  {...longPressHandler }></div>
)
}

  

上一篇:react路由


下一篇:Vue和React 有什么区别 优虐