如何在redux形式的模糊中访问验证结果

时间:2018-08-30 16:01:32

标签: reactjs redux-form

如果验证失败,我想停止任何onblur函数。我不确定该怎么做

这是字段

<Field
                                    label="Demand Ref"
                                    name="demand_ref"
                                    component={this.renderTextField}
                                    type="text"
                                    onBlur={e => this.onAfterSaveCell(e, 'demand_ref')}
                                    onFocus={e => this.onBeforeSaveCell(e, 'demand_ref')}
                                    validate={[validateDemandRef]}
                                    maxlength="15"
                                />

如果validate失败,我不希望运行onBlur中的任何内容。我该怎么办?

更新

如果我使用的是validate={[validateDemandRef]},我该如何传递到...some validation

更新2

如果它是const MyComponent = ({ handleSubmit, valid }) => (类,它的外观如何。 MyComponent是一堂课

1 个答案:

答案 0 :(得分:0)

使用isValidisInvalid选择器(https://redux-form.com/7.4.2/docs/api/selectors.md/

import React from 'react';
import { compose } from 'redux';
import { reduxForm, isValid } from 'redux-form';

const MyComponent = ({ handleSubmit, valid }) => (
  <form onSubmit={handleSubmit}>
    <Field
      label="Demand Ref"
      name="demand_ref"
      component={this.renderTextField}
      type="text"
      onBlur={valid && e => this.onAfterSaveCell(e, 'demand_ref')}
      onFocus={e => this.onBeforeSaveCell(e, 'demand_ref')}
      validate={[validateDemandRef]}
      maxlength="15"
    />
    <button type="submit">Submit</button>
  </form>
);

const FORM_NAME = 'my-form';

export default compose(
  reduxForm({
    form: FORM_NAME,
  }),
  connect(state => ({
    valid: isValid(FORM_NAME)(state),  // also there is an isInvalid selector
  })),
)(MyComponent);

用于状态组件的实现

import React, { PureComponent } from 'react';
import { compose } from 'redux';
import { reduxForm, isValid } from 'redux-form';

class MyComponent extends PureComponent {
  render() {
    const { handleSubmit, valid } = this.props;

    return (
      <form onSubmit={handleSubmit}>
        <Field
          label="Demand Ref"
          name="demand_ref"
          component={this.renderTextField}
          type="text"
          onBlur={valid && e => this.onAfterSaveCell(e, 'demand_ref')}
          onFocus={e => this.onBeforeSaveCell(e, 'demand_ref')}
          validate={[validateDemandRef]}
          maxlength="15"
        />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

const FORM_NAME = 'my-form';

export default compose(
  reduxForm({
    form: FORM_NAME,
  }),
  connect(state => ({
    valid: isValid(FORM_NAME)(state),  // also there is an isInvalid selector
  })),
)(MyComponent);