【问题标题】:How to conditionally disable the submit button with react-hook-form?如何使用 react-hook-form 有条件地禁用提交按钮?
【发布时间】:2021-03-23 02:27:08
【问题描述】:

找不到解决方案。
我正在使用react-hook-form,我想在表单为空时禁用提交按钮并启用,只要所有表单都至少写了一些东西。
我将如何使用react-hook-form 来做到这一点?

【问题讨论】:

    标签: reactjs react-hook-form


    【解决方案1】:

    你可以使用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" />

    【讨论】:

      【解决方案2】:

      到目前为止我发现的最佳解决方案是使用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模式解释:

      验证将在每个输入的更改事件上触发,并导致多次重新渲染。警告:这通常会对性能产生重大影响。

      【讨论】:

        【解决方案3】:
        const { 
            register, 
            handleSubmit, 
            formState: { isSubmitting, isDirty, isValid } // here
          } = useForm({ mode: "onChange" })
        
        
        <button
          type="submit"
          disabled={!isDirty || !isValid} // here
        >
          Comment
        </button>
        

        【讨论】:

        • 或者如果在嵌套组件中使用,您可以直接从const { isDirty, isValid } = useFormState(); 获取表单状态
        猜你喜欢
        • 2021-05-16
        • 1970-01-01
        • 1970-01-01
        • 2020-07-23
        • 1970-01-01
        • 2021-08-10
        • 2021-09-28
        • 1970-01-01
        • 2020-10-06
        相关资源
        最近更新 更多