【问题标题】:Disable button till all the form fields get filled in Formik禁用按钮,直到所有表单字段都填写在 Formik
【发布时间】:2020-11-12 02:41:45
【问题描述】:

我正在使用 Formik 表单。我里面有两个字段。我需要禁用保存按钮,直到两个字段都填满。

<Formik initialValues={initialValues} validationSchema={validate} onSubmit={() => this.handleSubmit()}>
  {({ values, handleChange, handleSubmit, setValues, isSubmitting }) => (
    <form onSubmit={handleSubmit} noValidate>
      <div>
        <div onClick={this.showDrawer}>
          <h6>Select Company </h6>
          <input name="customer" readOnly placeholder="Select" value={values.customer} type="text" />
        </div>
        <ErrorMessage component="span" name="customer" />
      </div>
      <div>
        <div onClick={this.showDrawer}>
          <h6>Select Driver</h6>
          <input name="driver" readOnly placeholder="Select" value={values.driver} type="text" />
        </div>
        <ErrorMessage component="span" name="driver"/>
      </div>
      <button type="submit" disabled={isSubmitting}>
        Save
      </button>
    </form>
  )}
</Formik>

【问题讨论】:

标签: javascript reactjs forms formik


【解决方案1】:
<Formik initialValues={initialValues} validationSchema={validate} onSubmit={() => this.handleSubmit()}>
  {({ values, handleChange, handleSubmit, setValues, isSubmitting, dirty, isValid }) => (
    <form onSubmit={handleSubmit} noValidate>
      <div>
        <div onClick={this.showDrawer}>
          <h6>Select Company </h6>
          <input name="customer" readOnly placeholder="Select" value={values.customer} type="text" />
        </div>
        <ErrorMessage component="span" name="customer" />
      </div>
      <div>
        <div onClick={this.showDrawer}>
          <h6>Select Driver</h6>
          <input name="driver" readOnly placeholder="Select" value={values.driver} type="text" />
        </div>
        <ErrorMessage component="span" name="driver"/>
      </div>
      <button type="submit" disabled={!(dirty && isValid)}>
        Save
      </button>
    </form>
  )}
</Formik>

【讨论】:

  • 请解释一下这段代码是如何解决问题的。
  • 虽然我感觉按钮部分应该是:&lt;button type="submit" disabled={dirty &amp;&amp; !isValid)}&gt;Save&lt;/button&gt;
【解决方案2】:
{
  ({ errors, ...others }) => (
  ...other components
  <button type="submit" disabled={isSubmitting || Object.keys(errors).length > 0}>
    Save
  </button> )
}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
猜你喜欢
  • 2018-01-22
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
相关资源
最近更新 更多