javascript - React 热键无法访问更新状态
问题描述
当输入指定的键盘快捷键时,我正在使用库GlobalHotKeys
提供的react-hotkeys
来触发某些事件。但是处理函数无法获取状态的更新值。以下是我使用的代码。
代码沙箱代码可在此处获得:此链接
import React from 'react'
import { GlobalHotKeys } from 'react-hotkeys'
function Playground() {
const [count, setCount] = React.useState(0)
const handleEvent = React.useCallback(() => {
console.log("Count Value now is: ", count)
}, [])
return (
<GlobalHotKeys
keyMap={{
FOCUS_BARCODE: 'alt+a'
}}
handlers={{
FOCUS_BARCODE: handleEvent
}}>
<div>
<h1>Here is count value: {count}</h1>
<button onClick={() => setCount((count) => count + 1)}> Increase Count</button>
</div>
</GlobalHotKeys>
)
}
export default Playground
现在发生了什么
任何时候我点击alt+a
,它的控制台日志都算作0
. 我点击了Increase count
按钮并增加了 的值,count
然后点击alt+a
仍然给出了count
to的值0
。
我需要的
我想count
用热键打印更新后的值。
解决方案
你必须添加allowchanges ..
<GlobalHotKeys
keyMap={{
FOCUS_BARCODE: 'alt+a'
}}
handlers={{
FOCUS_BARCODE: handleEvent
}}
allowChanges={true}
>
<div>
<h1>Here is count value: {count}</h1>
<button onClick={() => setCount((count) => count + 1)}> Increase Count</button>
</div>
</GlobalHotKeys>
推荐阅读
- java - 如何在 Spring-boot 2.x 中一起发送 MultiPart 和 RequestBody
- javascript - 输入数据到下一个输入时怎么办?
- java - 本地主机上的 Tomcat 服务器无法启动
- javascript -
。原型。 不适用于“this”关键字 - sql - 检查列是否存在然后从表中更改列?
- java - 继承类中的 Java 覆盖
- python - 如何禁用现有 gcp 云功能的“--allow-unauthenticated”标志?
- javascript - 如果不适合,Highcharts 会动态移动 dataLabel
- html - 如何创建像 html 表格这样的汇总表
- c - 指向函数内部的静态变量的指针。C