![](/img/trans.png)
[英]Enable/disable submit button with react-hook-form in onBlur mode
[英]How to conditionally disable the submit button with react-hook-form?
找不到解决方案。
我正在使用react-hook-form
并且我想在 forms 为空并启用时禁用提交按钮,只要所有 forms 至少有一些东西写入其中。
我将如何使用react-hook-form
做到这一点?
const {
register,
handleSubmit,
formState: { isSubmitting, isDirty, isValid } // here
} = useForm({ mode: "onChange" })
<button
type="submit"
disabled={!isDirty || !isValid} // here
>
Comment
</button>
到目前为止,我使用formState
并将模式设置为onChange
找到了最好的解决方案。
const { register, handleSubmit, formState } = useForm({
mode: "onChange"
});
在提交按钮上:
<button disabled={!formState.isValid}/>
基于这个问题: https://github.com/react-hook-form/react-hook-form/issues/77
文档中的 onChange 模式解释:
验证将在每个输入的更改事件上触发,并导致多次重新渲染。 警告:这通常会对性能产生重大影响。
您可以使用formState
=> isDirty
这意味着表单已被修改。
https://react-hook-form.com/api#formState
下面是formState
的一个工作示例:
https://codesandbox.io/s/react-hook-form-v6-formstate-ht098?file=/src/index.jsx:423-432
<input disable={formState.isDirty} type="submit" />
关闭,但我认为逻辑与其他评论略有不同。 关键是使用&&
运算符。 归功于 Formik 库的示例。
const { formState: { errors, isDirty, isValid } } = useForm()
///...
<button type="submit" disabled={!isDirty && !isValid}>
Continue
</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.