blog icon indicating copy to clipboard operation
blog copied to clipboard

React实现绑定长按和点击事件

Open xianzou opened this issue 3 years ago • 0 comments

React实现绑定长按和点击事件

使用Hooks实现长按和点击事件

export const useLongPressAndClick = (pressHandle, clickHandle) => {
    const flagRef = useRef(0);
    const interVal = useRef(0);
    const longPress = () => {
        clearInterval(interVal.current);
        interVal.current = 0;
        flagRef.current = 0;
        pressHandle();
    };

    const onClick = () => {
        clickHandle();
    };
    const touchStart = () => {
        // 设置定时器
        interVal.current = setInterval(() => {
            flagRef.current += 1;
        }, 500);
    };
    const touchEnd = () => {
        // 这里执行点击的操作,长按和点击互不影响
        if (!interVal.current){
            return false;
        }
        if (flagRef.current) {
            longPress();
        } else {
            clearInterval(interVal.current);
            flagRef.current = 0;
            interVal.current = 0;
            onClick();
        }
    };
    const touchmove = () => {
        if (interVal.current) {
            clearInterval(interVal.current);
            interVal.current = 0;
            flagRef.current = 0;
        }
    };

    return {
        touchStart,
        touchEnd,
        touchmove
    };
};

使用

import { useLongPressAndClick } from '@/utils/hooks';
const List = () =>{
    // 长按事件回调
    const pressHandle = () => {
        ...
    };
    // 点击事件回调
	const clickHandle =() => {
        ...
    }
   const { touchStart, touchEnd, touchmove } = useLongPressAndClick(pressHandle, clickHandle); 
    
   return (
   	<div
        className={styles.commitRow}
        onTouchStart={e => {
               e.preventDefault();
               e.stopPropagation();
               touchStart();
           }}
        onTouchMove={touchmove}
        onTouchEnd={e => {
               e.preventDefault();
               e.stopPropagation();
           }}
        >
           长按或点击
       </div>
   )
}

xianzou avatar Mar 10 '21 03:03 xianzou