简体   繁体   English

反应formik禁用提交按钮与表单有效性

[英]react formik disable submit button with form validity

I am using formik library for my react project.我正在为我的反应项目使用 formik 库。 I need to disable submit button initially when mandatory fields are empty or have any errors.当必填字段为空或有任何错误时,我最初需要禁用提交按钮。 I checked form status using below code.我使用以下代码检查了表单状态。

const formik = useFormik(false);

        <Formik
        initialValues={!location.state ? InvoiceInitalValues : location.state}
        validationSchema={POValidation} innerRef={formRef}
        onSubmit={(form, actions, formikHelper) => {
          console.log(form);
          console.log(formRef);
          setTimeout(() => {
            saveInvoice(form, actions, formikHelper);
            actions.setSubmitting(false);
          }, 1000);
        }}
      >
        {({
          handleSubmit,
          handleChange,
          setFieldValue,
          values,
          handleReset,
          errors,
          resetForm, isSubmitting


        }) 

I console logged form status using but form is always 'isValid: True'.我使用控制台记录表单状态,但表单始终为“isValid:True”。 Please check below image.请检查下图。 在此处输入图像描述

I printed it in the html also.我也在 html 上打印了它。 but always isValid is True.但始终 isValid 为 True。 I need to this for disable my button我需要这个来禁用我的按钮

printed status打印状态

 <p> {formik.isValid=== true ? "True" : "False"} </p>

I tried below code to disable my button我试过下面的代码来禁用我的按钮

<Button className="btn btn-primary mr-1" type="submit" disabled={!formik.isValid}>

Submit提交

Why formik form validity is always true, even mandatory fields are empty.为什么 formik 表单有效性总是正确的,即使是必填字段也是空的。 I spent more time to solve this.我花了更多时间来解决这个问题。 still could not fix this.仍然无法解决这个问题。 Anyone know to fix this任何人都知道解决这个问题

You created form using Formik component, but you are checking isValid on another formik instance created through useFormik hook.您使用Formik组件创建了表单,但是您正在通过useFormik钩子创建的另一个 formik 实例上检查isValid That's not right.那是不对的。

You should use either <Formik> or useFormik .您应该使用<Formik>useFormik

As you have written code using Formik component.正如您使用 Formik 组件编写的代码一样。 Here is how you access isValid property:以下是访问isValid属性的方法:

<Formik
  initialValues={!location.state ? InvoiceInitalValues : location.state}
  // ...
>
  {({
    values,
    handleChange,
    // ... 
    isValid // HERE
  }) => (
    <form onSubmit={handleSubmit}>
      <input
...

Here is a codesandbox .这是一个 代码框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM