Javascript 如何处理react web中的长按事件
各位!!我使用react和materialui库。我想分别处理点击事件和长按事件。我认为这个问题和异步设置状态有关,但现在,我不知道如何处理这个事件Javascript 如何处理react web中的长按事件,javascript,reactjs,web,material-ui,long-press,Javascript,Reactjs,Web,Material Ui,Long Press,各位!!我使用react和materialui库。我想分别处理点击事件和长按事件。我认为这个问题和异步设置状态有关,但现在,我不知道如何处理这个事件 const [isCommandHandled, setIsCommandHandled] = React.useState(null); const handleButtonPress = function (e) { setIsCommandHandled(false); console.log('ON_MOUSE_DOWN '
const [isCommandHandled, setIsCommandHandled] = React.useState(null);
const handleButtonPress = function (e) {
setIsCommandHandled(false);
console.log('ON_MOUSE_DOWN ' + isCommandHandled); // here value null
buttonPressTimer = setTimeout(handleLongPress, 1500, e);
}.bind(this);
const handleLongPress = (e) => {
if (!isCommandHandled) {
setIsCommandHandled(true);
console.log('TIMER_IS_EXECUTED' + isCommandHandled); //Here value false or null
// some other logic for long press event
}
clearTimeout(buttonPressTimer);
};
const handleButtonRelease = function (e) {
if (!isCommandHandled) {//isCommandHandled isn't updated here, as a result logic is executed always
// got regular click, not long press
// specific logic
setIsCommandHandled(true);
}
clearTimeout(buttonPressTimer);
};
把手按钮(e)}
onMouseUp={(e)=>把手按钮释放(e)}
>
```
您可以将setState与callback一起使用,并将设置的超时ID设置为state:
setIsCommandHandled((prevState)=>{
console.log("TIMER_IS_EXECUTED" + isCommandHandled); //Here value false or null
return true; });
工作示例:
您可以将setState与callback一起使用,并将设置的超时ID设置为state:
setIsCommandHandled((prevState)=>{
console.log("TIMER_IS_EXECUTED" + isCommandHandled); //Here value false or null
return true; });
工作示例:
谢谢你抽出时间。但我认为有一些问题。我想单独看比赛。我的意思是,如果我们得到简单的点击,我们不会为长按触发逻辑,反之亦然const handleButtonRelease=函数(e){console.log(“handleLongPress”,isCommandHandled)``如果我添加了前一行,我发现在鼠标向上的处理程序中,isCommandHandled变量总是false。我编辑了示例:看,长按计时器是执行的,单按感谢您花费的时间。但我认为有一些问题。我想单独捕获事件。我的意思是,如果我们只需简单单击,就不会触发长按和vis的逻辑反之亦然。``const handleButtonRelease=function(e){console.log(“handleLongPress”,isCommandHandled);``如果我添加了上一行,我会发现在mouse up handler中,isCommandHandled变量始终为false。我编辑了示例:查看长按计时器,然后单按