我正在使用 Next.js 构建一个网站,目前我正在尝试在按键时运行一个简单的函数。我遇到的问题是 onKeyDown 事件没有像我预期的那样被触发。我的代码如下:
; console.log("Key Pressed")}>
当前它放置在“main”元素中,这是该组件的顶部根元素。
我也尝试将 onKeyDown 事件放置在许多其他元素中,但没有成功。
我不确定是否是位置导致了问题,还是我对如何使用此事件缺乏了解。任何帮助将不胜感激。
至于现在,我只是希望它在控制台中写入一些内容,以便我可以看到它触发了。我尝试使用 onKeyPress 代替,并为事件分配一个函数而不是 lambda 表达式,这应该没有什么区别。
I'm building a website using Next.js, and currently I'm trying to get a simple function to run when pressing a key. The problem I'm having is that the onKeyDown event isn't being triggered like I expected. My code is as follows:
<main onKeyDown={e => console.log("Key pressed")}>
Currently it's placed in the "main" element, which is the top root element of this component.
I've tried placing the onKeyDown event in many of the other elements as well, without luck.
I'm not sure if it's the placement which causes issues or my lack of understanding of how to use this event. Any help would be appreciated.
As for now I simply want it to write something in the console so that I can see that it triggers. I've tried using onKeyPress instead, as well as assigning a function to the event instead of a lambda expression, which shouldn't make a difference.
发布评论
评论(1)
在您的组件中,使用
useEffect
向文档添加(和删除)事件侦听器。您甚至可以创建一个自定义挂钩(注意依赖项列表):
In your component, use
useEffect
to add(and remove) the event listener to the document.You may even make a custom hook (beware of the dependency list):