【问题标题】:How to simulate long press with react js?如何用 React js 模拟长按?
【发布时间】:2019-11-03 21:17:20
【问题描述】:

我想用点击事件触发长按事件。 react js有什么办法吗?

与此相近的是 jQuery trigger() 函数。但我想要触发器(“longPress”)之类的东西,或者用左键点击打开右键菜单。两者都提到(长按触发器/打开右键菜单)对我来说是理想的

【问题讨论】:

    标签: javascript reactjs touch-event


    【解决方案1】:

    这样的事情怎么样:

    const myComponent = () => {
    
        let clickHoldTimer = null;
    
        const handleMouseDown = () => {
            clickHoldTimer = setTimeout(() => {
                //Action to be performed after holding down mouse
            }, 1000); //Change 1000 to number of milliseconds required for mouse hold
        }
    
        const handleMouseUp = () => {
            clearTimeout(clickHoldTimer);
        }
    
        return (
            <div onMouseDown={handleMouseDown} onMouseUp={handleMouseUp} />
        )
    
    }
    

    【讨论】:

    • 我想这样做的原因是我希望单击 ios 菜单。我相信这无济于事,但我感谢您的回答。谢谢朋友
    【解决方案2】:

    您可以通过获取保持时间来实现此技巧

    https://stackblitz.com/edit/react-d1txdm

    export default function App() {
      let triggerTime;
      return (
        <div>
          <h1>Try on Google Chrome Desktop</h1>
          <p>Open the console log to see how the event gets triggered.</p>
          <p>The event should not get triggered if there is a long click.</p>
          <img
            src="https://via.placeholder.com/200.png/09f/fff"
            onClick={(e) => {
              if (triggerTime > 1000) return;
              else console.log('normal click');
            }}
            onMouseDown={() => {
              triggerTime = new Date().getTime();
            }}
            onMouseUp={() => {
              let thisMoment = new Date().getTime();
              triggerTime = thisMoment - triggerTime;
            }}
          />
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      • 2015-04-24
      • 2019-12-24
      相关资源
      最近更新 更多