javascript - How do I set up an 'onKeyPress' handler on a <canvas> in react? - Stack Overflow

admin2025-04-22  0

I am familiar with React and its event system, but I can't seem to get the onKeyPress event to fire on a <canvas> element. In fact, I can't get it to fire on a <div> either.

Here is the relevant code

class MyComponent extends React.Component {
    render() {
        return (
            <canvas onKeyPress={() => console.log('fired')} />
        )
    }
}

It works fine if I change the <canvas> to be an <input>, but does not work for <div>. Does this mean that react simply does not support keyPress events on canvas elements? What am I overlooking?

I am familiar with React and its event system, but I can't seem to get the onKeyPress event to fire on a <canvas> element. In fact, I can't get it to fire on a <div> either.

Here is the relevant code

class MyComponent extends React.Component {
    render() {
        return (
            <canvas onKeyPress={() => console.log('fired')} />
        )
    }
}

It works fine if I change the <canvas> to be an <input>, but does not work for <div>. Does this mean that react simply does not support keyPress events on canvas elements? What am I overlooking?

Share Improve this question asked Oct 14, 2015 at 5:06 user4683322user4683322
Add a ment  | 

2 Answers 2

Reset to default 6

Just assign tabIndex to the element for getting the focus.

<canvas tabIndex="0" onKeyPress={ () => console.log( 'fired' ) } />
canvas.addEventListener('keydown', function(event) {
    alert('keydown');
        }, false);

Check if you can fire the above event :)

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745289955a294623.html

最新回复(0)