javascript - 如何在React Web中处理长按事件

标签 javascript reactjs web material-ui long-press

大家好!我使用 React 和 Material ui 库。我想分别处理点击事件和长按事件。我认为问题与异步设置状态有关,但现在我不知道如何处理此事件

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);
  };

<IconButton 
             onMouseDown={(e) => handleButtonPress(e)}
             onMouseUp={(e) => handleButtonRelease(e)}
          >
    ```

最佳答案

您可以使用带有回调的setState并将设置的超时ID放入state:

 setIsCommandHandled((prevState)=>{ 
        console.log("TIMER_IS_EXECUTED" + isCommandHandled); //Here value false or null
        return true; });

工作示例: https://codesandbox.io/s/material-demo-gc0le

关于javascript - 如何在React Web中处理长按事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59136239/

相关文章:

javascript - 具有完整日历的上下文菜单,在日历和上下文菜单之间传递数据

javascript - html - 如何在 Firefox、Opera、Safari 下增加单选按钮的大小

javascript - react-fullpage.js - 如何在特定部分(而不是第一部分)加载网站?

php - 使用 iOS 缓存 Web 表单

web - 哪些个人数据不应该在网络上发布?

javascript - 我怎样才能点击带有CSS动画的div?

javascript - SVG donut 切片作为路径元素(环形扇区)

excel - 使用 OfficeJs 和 ReactJS 在 Excel 插件中保存功能

reactjs - 试图准确理解当我使用 useEffect 时发生了什么

javascript - 使用 Firebase 为 Web 应用创建房间