如何在< canvas>上设置'onKeyPress'处理程序在反应吗? [英] How do I set up an 'onKeyPress' handler on a <canvas> in react?
本文介绍了如何在< canvas>上设置'onKeyPress'处理程序在反应吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我熟悉React及其事件系统,但似乎无法在< canvas>
元素上触发onKeyPress事件.实际上,我也无法在< div>
上触发它.
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.
这是相关代码
class MyComponent extends React.Component {
render() {
return (
<canvas onKeyPress={() => console.log('fired')} />
)
}
}
如果我将< canvas>
更改为< input>
,效果很好,但不适用于< div> 代码>.这是否意味着react根本不支持canvas元素上的keyPress事件?我忽略了什么?
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?
推荐答案
只需将 tabIndex
分配给元素即可获得焦点.
Just assign tabIndex
to the element for getting the focus.
<canvas tabIndex="0" onKeyPress={ () => console.log( 'fired' ) } />
这篇关于如何在< canvas>上设置'onKeyPress'处理程序在反应吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文