Simulate click event on react element

后端 未结 7 1927
孤独总比滥情好
孤独总比滥情好 2020-12-03 03:06

I\'m trying to simulate a .click() event on a React element but I can\'t figure out why it is not working (It\'s not reacting when I\'m firing the

相关标签:
7条回答
  • 2020-12-03 03:53

    React tracks the mousedown and mouseup events for detecting mouse clicks, instead of the click event like most everything else. So instead of calling the click method directly or dispatching the click event, you have to dispatch the down and up events. For good measure I'm also sending the click event but I think that's unnecessary for React:

    const mouseClickEvents = ['mousedown', 'click', 'mouseup'];
    function simulateMouseClick(element){
      mouseClickEvents.forEach(mouseEventType =>
        element.dispatchEvent(
          new MouseEvent(mouseEventType, {
              view: window,
              bubbles: true,
              cancelable: true,
              buttons: 1
          })
        )
      );
    }
    
    var element = document.querySelector('div[class="UFIInputContainer"]');
    simulateMouseClick(element);
    

    This answer was inspired by Selenium Webdriver code.

    0 讨论(0)
提交回复
热议问题