Simulate click event on react element

后端 未结 7 1976
孤独总比滥情好
孤独总比滥情好 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:33

    If you don't define a class in your component, and instead you only declare:

    function App() { ... }
    

    In this case you only need to set up the useRef hook and use it to point/refer to any html element and then use the reference to trigger regular dom-events.

    import React, { useRef } from 'react';
    
    function App() {
      const inputNameRef = useRef()
      const buttonNameRef = useRef()
      
      function handleKeyDown(event) {
        // This function runs when typing within the input text,
        // but will advance as desired only when Enter is pressed
        if (event.key === 'Enter') {
          // Here's exactly how you reference the button and trigger click() event,
          // using ref "buttonNameRef", even manipulate innerHTML attribute
          // (see the use of "current" property)
          buttonNameRef.current.click()
          buttonNameRef.current.innerHTML = ">>> I was forced to click!!"
        }
      }
      
      function handleButtonClick() {
        console.log('button click event triggered')
      }
      
      return (
        
    ) } export default App;

提交回复
热议问题