繁体   English   中英

使用Redux表单,如果未填写任何字段,如何禁用提交按钮?

[英]Using Redux Form, how can I disable the submit button if no fields have been filled out?

我正在使用Redux Form v.7.1.2,并试图首先禁用“提交”按钮。 当用户激活changekeyup事件时,我希望表单检查表单中的任何表单字段是否具有任何值。 如果是这样,我希望启用提交按钮。 我没有任何必填字段。 我只需要确保其中至少一个值已填写即可。

我已经在jQuery中实现了这一点:

// Change disabled attribute on search box submit button depending on if there is a value in any field
  $searchFormFields.on('change keyup', function() {
    $('#search-box-search-btn').prop('disabled', true);
    $searchFormFields.each(function() {
      if ($(this).val().length > 0) {
        $('#search-box-search-btn').prop('disabled', false);
        return false; // break the loop
      }
    });
  });

我现在正在将该站点转换为使用React和Redux,而且我完全不知道从哪里开始尝试使其工作。 有任何想法吗?

如果您只想检查没有填写的字段,可以使用以下行:

<button type="submit" disabled={this.props.pristine}>Submit</button>

pristine是redux-form所添加的一项道具,如果表单中未填写任何字段,您可以引用该道具。 您可以在他们的API文档中查看更多信息。 它将当前表单值与表单上的初始值进行比较。

事实证明,如果自上次提交以来未更改表单,则实际上我需要禁用该按钮。

为了检查这种情况,您可以在提交表单时将当前值指定为初始值。 然后,当确定表单是否pristine ,redux-form会将当前值与最近提交时设置的最后初始值进行比较。

import { Field, reduxForm } from 'redux-form';

class SearchFilters extends Component {
  constructor(props) {
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit(values) {
    // Check if the form values have changed since the last submit
    // The dirty boolean (signifies if the form has changed from its initial values) is established by redux-form by comparing the currently entered values to the initial form values
    // After we identify the form as having been changed, we will send the new form values to replace the original initial form values so redux-form is always comparing the current form values against the last submitted form values
    if (this.props.dirty) {
      // Set the initial values for the form on the redux store (This is used by redux form to compare the current values to the initial values so we can determine if there are new values since the last submit)
      this.props.initialize(values);
    }
  }

  renderField(field) {
    return (
      <div className="search-parameter">
        <input type="text" {...field.input} />
      </div>
    );
  }

  render() {
    const { handleSubmit, submitting, invalid } = this.props;

    return (
      <form onSubmit={handleSubmit(this.onSubmit)} >
        <Field
          component={this.renderField}
          key="keyword"
          name="keyword"
        />
        <Field
          component={this.renderField}
          key="type"
          name="type"
        />
        <button
          type="submit"
          disabled={submitting || pristine || invalid}
        >
          Search
        </button>
      </form>
    );
  }
}

export default reduxForm({
  validate,
  form: 'SearchFiltersForm',
})(connect(mapStateToProps, null)(SearchFilters));

暂无
暂无

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

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