You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Hook Form中window事件监听内handleSubmit无法触发问题

问题原因与解决方案

核心问题

你在键盘事件中调用handleSubmit后,没有执行它返回的提交函数。handleSubmit的作用是生成并返回一个包含表单验证与提交逻辑的函数,而非直接触发提交。按钮能正常工作是因为代码里执行了这个返回的函数(action.action()),但键盘事件里只调用了handleSubmit(...)生成函数,却没执行它。

修复步骤

1. 执行handleSubmit返回的函数

修改enterHandler中的代码,在handleSubmit(...)后加(),触发提交逻辑:

const enterHandler = (e: KeyboardEvent) => {
  if (e.code === 'Enter' || e.code === 'NumpadEnter') {
    console.log('enterHandler');
    // 执行handleSubmit返回的提交函数
    handleSubmit(
      (data) => console.log('data :', data),
      (errors) => console.log('invalid data :', errors)
    )();
  }
};

2. 修正useEffect依赖数组

handleSubmit是useForm返回的函数,会随组件状态更新,需要加入useEffect的依赖数组,避免闭包问题导致使用旧的函数实例:

useEffect(() => {
  // ... 其他代码

  window.addEventListener('keydown', enterHandler, false);

  return () => window.removeEventListener('keydown', enterHandler, false);
}, [id, handleSubmit]); // 加入handleSubmit

3. 可选:移除不必要的preventDefault

如果输入框是数字类型,e.preventDefault()可能会干扰输入框的默认行为(比如回车确认输入),可以移除该语句,仅在确认提交时按需阻止默认行为。

额外优化:按钮onClick的写法

原按钮代码onClick={action.action()}存在问题——每次组件渲染都会执行action.action(),可能导致不必要的表单提交。正确写法应该是传递函数引用:

<Button onClick={action.action} ...>{action.text}</Button>

(如果BaseModal要求必须执行函数,可改为onClick={() => action.action()})

内容的提问来源于stack exchange,提问作者Lucas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 15:40:07