简体   繁体   中英

Not able to dispatch KeyDown event to React Component

I would like to dispatch onKeyDown events from a body element too a div inside of the body.

I am using React and have tried adding an onKeyDown event listener to my body tag in the componentDidMount function of my React component.

componentDidMount() {
    document.getElementById("main-content").onkeydown = event => {
        document.getElementById("Keyboard").dispatchEvent(event);
    }
}

I expected the keydown event to be dispatched to the Keyboard component, but instead I receive the error listed below.

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.

Any help would be appreciated!

Can you not hardcode it onto your div element?
Use this question as reference if you can.

If you can't harcode it maybe try this:

    document.querySelector('#yourDiv').addEventListener('keydown', function (event) {
      console.log(event.key) //Change this to whatever you want it to do
    })

Then in your HTML give your div a tabindex="0" property.

The tabindex property:

tabindex="0" allows a non-form/link/object element to be placed in the default navigation order, allowing any element to be focusable and trigger interaction.

More info here

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