React识别长按操作

​定时器仍会保留一个数字值,需要手动清零。
React分别设置绑定onTouchStart() onTouchMove() onTouchEnd()实现长按识别

onTouchStart(){
this.timeOutEvent = setTimeout(function() {
this.timeOutEvent = 0;
console.log(‘你长按了’);
}, 400);

}

onTouchMove() {  
    clearTimeout(this.timeOutEvent);  
    this.timeOutEvent = 0;  
} 
onTouchEnd() {  
    clearTimeout(this.timeOutEvent);  
    if (this.timeOutEvent != 0) {  

        console.log('你点击了');  
    }  
    return false;  
}  
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React 17 并没有直接提供按事件的功能,但你可以通过使用原生 DOM 的方式来实现。你可以在 React 组件中添加一个 ref 属性,并将其设置为一个函数,然后在该函数中获取对应的 DOM 元素。接着,你可以在该 DOM 元素上监听 "mousedown" 和 "mouseup" 事件,并使用 setTimeout 函数来实现按功能。 具体实现如下所示: ```jsx import React, { useRef } from 'react'; function LongPressButton() { const buttonRef = useRef(null); let timer = null; const handleMouseDown = () => { timer = setTimeout(() => { console.log('Long press triggered!'); }, 1000); }; const handleMouseUp = () => { clearTimeout(timer); }; return ( <button ref={buttonRef} onMouseDown={handleMouseDown} onMouseUp={handleMouseUp} > Long Press Button </button> ); } export default LongPressButton; ``` 在上面的代码中,我们使用了 useRef 钩子来创建了一个 buttonRef 引用。在组件渲染时,我们将该引用赋值给了 button 元素。然后,我们在 button 元素上监听了 onMouseDown 和 onMouseUp 事件,并分别触发 handleMouseDown 和 handleMouseUp 函数。在 handleMouseDown 函数中,我们使用 setTimeout 函数来实现按功能。在 handleMouseUp 函数中,我们清除了定时器,以避免按事件被错误地触发。 需要注意的是,上面的代码只是一个简单的示例,并没有考虑到一些复杂的情况。例如,在触发按事件之前,用户可能会拖动鼠标或者取消点击等操作。因此,在实际开发中,你可能需要对代码进行一些修改和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值