Enable/disable onBlur 模式下带有 react-hook-form 的提交按钮

Enable/disable submit button with react-hook-form in onBlur mode

我在 onChange 模式下使用 react-hook-form。我 enable/disable 提交按钮取决于验证状态。它工作得很好。

现在我必须切换到 onBlur 模式。目前的解决方案不再按预期工作。当所有字段都有效时,我希望提交按钮立即启用。现在它只有在我点击最后一个字段时才会启用。我应该在我的代码中更改什么才能按预期工作?

  const { register, errors, handleSubmit, formState } = useForm({
    mode: "onChange" // I want to change it to onBlur
  });
  const { isValid } = formState;

...

<input disabled={!isValid} type="submit" />

这是一个例子:https://codesandbox.io/s/react-hook-form-disable-submit-button-onblur-0293x?file=/src/index.js

更新解决方案: NearHuscarl 的回答有助于找到解决方案。 我必须停留在 onChange 模式并自己处理错误消息的显示。如果该字段位于 formState 的 touchedFields 对象中,我只会显示错误。

  const form = useForm({
    mode: "onChange" // I want to change it to onBlur
  });
  const { register, handleSubmit, formState } = form;
  const { isValid, touchedFields, errors } = formState;

...

        <div>
          <label htmlFor="firstName">First Name</label>
          <input
            name="firstName"
            placeholder="bill"
            {...register("firstName", { minLength: 3 })}
          />
          {errors.firstName && touchedFields.firstName && (
            <p>"minimum length is 3"</p>
          )}
        </div>

工作示例:https://codesandbox.io/s/react-hook-form-disable-submit-button-onblur-forked-v8m05?file=/src/index.js

这正是 onBlur 模式的工作原理。来自 docs:

Validation will trigger on the blur event.

因此,当您的所有字段都变为有效时,它不会触发验证。但是,一旦您在当前聚焦的字段之外单击,该字段的 blur 事件就会触发,该事件会运行并通过验证检查,然后才会再次启用提交按钮。

解决方案是改回onChange模式,每次输入值变化时触发验证。