简体   繁体   English

Reactjs 当按下空格键而不是在按钮上时触发带有 keydown 的按钮

[英]Reactjs trigger button with keydown when pressing space bar not on the button

Right now, I'm trying to create a button that activates OnKeyDown, but that command only works when the user is hovering over the button and has selected it.现在,我正在尝试创建一个激活 OnKeyDown 的按钮,但该命令仅在用户将鼠标悬停在按钮上并选择它时才有效。 Is there a way to use OnKeyDown so you can hover over an img on the other side of the screen, press space bar, and activate the button.有没有一种方法可以使用 OnKeyDown,这样您就可以在屏幕另一侧的 img 上按 hover,按空格键,然后激活按钮。 something like就像是

render(){
return(
<div>

<button onKeyDown = {this.dostuff}/>
<img src = {thing}/>
</div>

);

}

Except when hovering over the image and pressing space the button is activated.除非将鼠标悬停在图像上并按下空格键,否则该按钮将被激活。

You can achieve this by using useEffect() hook, similar to componentDidMount() , and by doing so you can add a global window event listener to your code in the useEffect() function once the component has mounted to the screen.您可以通过使用useEffect()挂钩来实现这一点,类似于componentDidMount() ,并且通过这样做,您可以在useEffect() function 中的代码中添加一个全局事件侦听器,一旦组件安装到屏幕上。

Code sample in codesandbox codesandbox中的代码示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM