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

使用react-hook-form时onBlur事件无法触发的技术求助

问题

react-hook-form本身功能正常,但给输入框绑定onBlur回调时出现异常:onFocus事件能正常触发,但把焦点移到其他输入框或别处时,onBlur完全不触发。移除react-hook-form的register特性后,onBlur可正常工作,只有使用register时失效。

环境版本:

  • "react-hook-form": "^7.41.1"
  • "react": "^18.2.0"

相关代码示例:

<div className="pb-5">
    <label
        className="block text-sm font-medium mb-1"
        htmlFor="name"
    >
        Name <span className="text-rose-500">*</span>
    </label>
    <input
        id="name"
        className="form-input w-full ml-2"
        type="text"
        defaultValue={projectState.project.app.name ?? '-'}
        name="name"
        onFocus={() => {
            console.log('got focus')
        }}
        onBlur={(event) => {
            console.log('lost focus')
        }}
        {...register('name', {
                required: {value: true, message: "Name is required"},
            },
        )}
    />
    {errors.name && <p className={`ml-2 mt-1 text-red-600`}>
        <span>{errors.name.message}</span>
    </p>}
</div>

解决方案

原因是register方法会生成并覆盖输入框的原生onBlur事件,你直接写在input上的onBlur会被register返回的事件覆盖掉。推荐两种解决方式:

方式一:将自定义onBlur传入register配置项

把你的onBlur逻辑放到register的第二个参数里,react-hook-form会在自身内置的onBlur逻辑执行后,调用你的自定义回调,既不影响表单校验,也能触发你的逻辑:

<input
    id="name"
    className="form-input w-full ml-2"
    type="text"
    defaultValue={projectState.project.app.name ?? '-'}
    name="name"
    onFocus={() => {
        console.log('got focus')
    }}
    {...register('name', {
            required: {value: true, message: "Name is required"},
            onBlur: (event) => {
                console.log('lost focus')
            }
        },
    )}
/>

方式二:调整register展开顺序(不推荐)

如果想保留原生写法,可以把{...register(...)}放在onBlur之前,这样自定义的onBlur会覆盖register生成的事件,但这种方式可能导致react-hook-form的onBlur校验逻辑失效,除非你不需要表单的失焦校验:

<input
    id="name"
    className="form-input w-full ml-2"
    type="text"
    defaultValue={projectState.project.app.name ?? '-'}
    name="name"
    {...register('name', {
            required: {value: true, message: "Name is required"},
        },
    )}
    onFocus={() => {
        console.log('got focus')
    }}
    onBlur={(event) => {
        console.log('lost focus')
    }}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 11:11:17