简体   繁体   English

如何处理反应中的长按事件 web

[英]How handle long press event in react web

everyone.每个人。 I use react and material ui library.我使用反应和材料 ui 库。 I want to handle click event and long-press event separately, I think problem related to async set state, but for now, I don't know how to handle this events我想分别处理点击事件和长按事件,我认为问题与异步设置 state 有关,但目前,我不知道如何处理这些事件

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

You can use setState with callback and put the set timeout ID to state:您可以将 setState 与回调一起使用,并将设置的超时 ID 置于状态:

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

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

This is how I handle a long press:这就是我处理长按的方式:

//import Hooks
import { useState, useEffect } from "react";

const Component = () => {
  //pressState
  const [pressed, setPressed] = useState();

  //handleLongPress
  useEffect(() => {
    const timer = pressed
      ? setTimeout(() => {
          console.log(pressed, "got pressed!");
        }, 1300)
      : null;
    return () => clearTimeout(timer);
  }, [pressed]);

  //pressedElement
  return (
    <div
      onMouseDown={(e) => setPressed(e.target)}
      onMouseUp={() => setPressed()}
      style={{ backgroundColor: "lightgreen" }}
    >
      Press me
    </div>
  );
};

export default Component;

Tested here: https://codesandbox.io/s/bold-bose-7vx3qg在这里测试: https://codesandbox.io/s/bold-bose-7vx3qg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM