正如@aadlc所说,解决方案是将模式设置为onChange
or all
。我会解释原因。
来自react-hook-formAPI docs https://react-hook-form.com/api:
mode: onChange | onBlur | onSubmit | onTouched | all = 'onSubmit'
Name |
Type |
Description |
onSubmit (Default) |
string |
Validation will trigger on the submit event and invalid inputs will attach onChange event listeners to re-validate them. |
onBlur |
string |
Validation will trigger on the blur event. |
|
|
|
onChange |
string |
Validation will trigger on the change event with each input, and lead to multiple re-renders. Warning: this often comes with a significant impact on performance. |
|
|
|
onTouched |
string |
Validation will trigger on the first blur event. After that, it will trigger on every change event. |
all |
string |
Validation will trigger on the blur and change events. |
在您的代码中,表单模式是onBlur
。这意味着验证被触发blur
事件(取消输入焦点)。当您选择该选项时n+1
,它触发选项的模糊事件n
.
例如就在您选择第 6 个选项(无效)之前,blur
事件从第 5 个选项(有效)触发,因为您不再关注它,并从选项 1-5 进行验证,因此您必须检查第 7 个选项以重新验证从 1 到 6 的选项。
-- select up to 5 options --
select option 4
blur event fires from option 4 -> validate -> pass
select option 5
blur event fires from option 5 -> validate -> pass
select option 6
blur event fires from option 6 -> validate -> fail
select option 7
将验证模式更改为onChange
将验证after change
当所有值都是最新时,事件被触发:
-- select up to 5 options --
select option 4
blur event fires from option 4
select option 5
change event fires from option 5 -> validate -> pass
blur event fires from option 5
select option 6
change event fires from option 6 -> validate -> fail
blur event fires from option 6
select option 7
change event fires from option 7 -> validate -> fail
将验证模式更改为all
将验证两者blur
and change
事件,这在此工作流程中可能有点过分,但它也有效。