我使用 useKey 来响应 Enter。
const [isFocused, setIsFocused] = useState(false);
useKey("Enter", ev => {
console.log("ev, isFocused -> ", ev, isFocused);
});
但是,打印的 isFocus 值始终为假,即使它已更改。
如何防止 useState 变量被冻结为初始值?
useKey
钩子支持依赖项(第 4 个参数(:
const useKey = (key: KeyFilter, fn: Handler = noop, opts: UseKeyOptions = {}, deps: DependencyList = [key])
用useCallback
包装事件处理程序并将其依赖项设置为isFocused
,然后将事件处理程序作为依赖项传递给useKey
。如果isFocused
发生变化,eventHandler
会发生变化,useKey
将相应地更新:
const eventHandler = useCallback(ev => {
console.log("ev, isFocused -> ", ev, isFocused);
}, [isFocused])
useKey("Enter", eventHandler, {}, [eventHandler]);