使用react-hook-form时不会触发React.js onBlur事件

问题描述 投票:0回答:1

react-hook-form 工作得很好。问题是当我想在输入字段上附加 onBlur 回调时。 onFocus 工作得很好,但是当我将焦点转移到其他输入字段或其他任何地方时,onBlur 事件不会被触发。

当我从react-hook-form中删除寄存器功能时,onBlur工作得很好,但当我使用react-hook-form中的寄存器时,它不会被触发。

...

“react-hook-form”:“^7.41.1”,

“反应”:“^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>

我尝试将回调附加到 onBlur 事件。不使用react-hook-form 时会触发该事件。 当我使用react-hook-form时,onBlur事件没有被触发,只有onFocus被触发

reactjs react-hook-form
1个回答
3
投票

register
函数覆盖
value
name
onChange
onBlur
属性

向 onBlur 添加逻辑:


const {onBlur, ...fieldProps} = register('name', {
   required: {value: true, message: "Name  is required"},
})

return (
     // ...
     <input
        id="name"
        className="form-input w-full ml-2 "
        type="text"
        onFocus={() => {
            console.log('got focus')
        }}
        onBlur={(event) => {
            console.log('lost focus')
            onBlur()
        }}
        {...fieldProps}
    />
    // ...
  )

参考

© www.soinside.com 2019 - 2024. All rights reserved.