[英]Long Press button in react
這可能真的很簡單,但任何人都知道如何長按按鈕做出反應。 就像一個按鈕,如果你按住 2 秒鍾它被“點擊”,否則它不是。 是否有針對此的反應鼠標事件? 也許我以某種巧妙的方式使用 onMouseDown 事件?
您可以嘗試的其中一種技巧是注意“onMouseDown”事件觸發的時間以及“onMouseUp”觸發的時間。
如果這些時間之間的差值大於等於 2 秒,則可以執行您想要的操作。
您必須編寫邏輯來檢查時間差和要執行的代碼,該方法將在觸發 'onMouseUp' 事件時執行。
delay = 2000;
startPress = null;
function mouseDown() {
startPress = Date.now();
}
function mouseUp() {
if(Date.now() - startPress > delay)
{
// your code
}
}
我使用以下內容創建了一個按鈕,該按鈕在您按住按鈕時動態更改類。 使用setInterval
而不是setTimeout
簡化了操作,因為我們自己管理結束計數。 我們不做任何類型的 DateTime 計算,我們可以通過觀察currentCount
來主動監控當前的延遲毫秒。
我使用 DaisyUI 作為我的組件框架,但可以使用任何 CSS 類。
import { useCallback, useEffect, useRef, useState } from 'react';
export type LongPressButtonProps = {
/** Text that will appear within the button */
buttonText: string;
/** Function to run once delay has been exceeded */
onExecute: () => void;
/** How long should be button be held before firing onExecute */
delayMs: number;
/** How frequently should the count be updated */
refreshMs: number;
};
const LongPressButton = ({
delayMs,
onExecute,
buttonText,
refreshMs = 100,
}: LongPressButtonProps) => {
const [mouseDown, setMouseDown] = useState(false);
const [currentCount, setCurrentCount] = useState(0);
const intervalRef = useRef<NodeJS.Timer>();
const [buttonClass, setButtonClass] = useState('btn-primary');
const onInterval = useCallback(() => {
setCurrentCount((c) => c + refreshMs);
}, [setCurrentCount, refreshMs]);
useEffect(() => {
if (mouseDown) intervalRef.current = setInterval(onInterval, refreshMs);
if (!mouseDown && intervalRef.current) {
clearInterval(intervalRef.current);
setCurrentCount(0);
setButtonClass(`btn-primary`);
}
}, [onInterval, delayMs, mouseDown, refreshMs]);
useEffect(() => {
if (currentCount > 0) setButtonClass(`btn-error`);
if (currentCount > delayMs) {
onExecute();
setCurrentCount(0);
}
}, [currentCount, delayMs, onExecute]);
return (
<button
className={`btn ${buttonClass}`}
onMouseDown={() => setMouseDown(true)}
onMouseUp={() => setMouseDown(false)}
onMouseLeave={() => setMouseDown(false)}
onTouchStart={() => setMouseDown(true)}
onTouchEnd={() => setMouseDown(false)}
style={{ transition: `${delayMs}ms` }}
>
{buttonText}
</button>
);
};
export default LongPressButton;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.