onClick works but onDoubleClick is ignored on React component

后端 未结 6 476
轻奢々
轻奢々 2020-12-05 03:38

I am building a Minesweeper game with React and want to perform a different action when a cell is single or double clicked. Currently, the onDoubleClick functi

6条回答
  •  有刺的猬
    2020-12-05 04:16

    you can use a custom hook to handle simple click and double click like this :

    function useSimpleAndDoubleClick(actionSimpleClick, actionDoubleClick, delay = 250) {
        const [click, setClick] = useState(0);
    
        useEffect(() => {
            const timer = setTimeout(() => {
                // simple click
                if (click === 1) actionSimpleClick();
                setClick(0);
            }, 300);
    
            // click in a delay < 250 = double click detected
            if (click === 2) actionDoubleClick();
    
            return () => {
                clearTimeout(timer);
            }
        }, [click]);
    
        return () => {
            setClick(prev => prev + 1);
        };
    }
    

    then in your component you can use :

    const click = useSimpleAndDoubleClick(callbackClick, callbackDoubleClick);
    
    

提交回复
热议问题