简体   繁体   中英

How to simulate long press with react js?

I want to trigger long press event with click event. is there any way to that in react js?

something close to this, is the jQuery trigger() function. but i want something like trigger("longPress") or open up right click menu with left click in react. both mentioned (long press trigger / open up right click menu) are ideal for me

you can do this hack by get hold time

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

What about something like this:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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