【发布时间】:2021-03-23 02:27:08
【问题描述】:
找不到解决方案。
我正在使用react-hook-form,我想在表单为空时禁用提交按钮并启用,只要所有表单都至少写了一些东西。
我将如何使用react-hook-form 来做到这一点?
【问题讨论】:
找不到解决方案。
我正在使用react-hook-form,我想在表单为空时禁用提交按钮并启用,只要所有表单都至少写了一些东西。
我将如何使用react-hook-form 来做到这一点?
【问题讨论】:
你可以使用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" />
【讨论】:
到目前为止我发现的最佳解决方案是使用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模式解释:
验证将在每个输入的更改事件上触发,并导致多次重新渲染。警告:这通常会对性能产生重大影响。
【讨论】:
const {
register,
handleSubmit,
formState: { isSubmitting, isDirty, isValid } // here
} = useForm({ mode: "onChange" })
<button
type="submit"
disabled={!isDirty || !isValid} // here
>
Comment
</button>
【讨论】:
const { isDirty, isValid } = useFormState(); 获取表单状态