如何处理 React Web 中的长按事件

How handle long press event in react web

各位!我使用 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 放入状态:

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

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