【问题标题】:redux-form: trigger Form onSubmit after Input onChangeredux-form: Input onChange 后触发 Form onSubmit
【发布时间】:2016-12-18 12:55:35
【问题描述】:

我在 redux 表单中有一组简单的单选按钮。我需要单选按钮组的onChange事件来触发表单的onSubmit事件。

我正在使用 redux-form v5.3.1

设置

RadioFormContainer.js

class RadioFormContainer extends Component {
  render() {
    const {submit} = this.props;
    return (
      <RadioForm submit={submit} />
    )
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    submit: function(values, dispatch) {
      // API call after validation
    }
  }
};

RadioForm.js

class RadioForm extends Component {
  render() {
    const {
      submit, // custom post-validation handler
      // via redux form decorator:
      handleSubmit,
      submitting
    } = this.props;
    return (
      <form onSubmit={handleSubmit(submit)}>
        <input {...radioField}
               checked={radioField.value == "one"}
               type="radio"
               value="one"
               disabled={submitting} />
        <input {...radioField}
               checked={radioField.value == "two"}
               type="radio"
               value="two"
               disabled={submitting} />
      </form>
    );
  }
}

尝试过的实现,不工作

1.从componentWillReceiveProps 拨打handleSubmit RadioForm

kyleboyle 的proposal here 根本不起作用。当我从componentWillReceiveProps 呼叫nextProps.handleSubmit 时,我得到this familiar errorUncaught Error: You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop

componentWillReceiveProps(nextProps) {
  if (nextProps.dirty && nextProps.valid) {
    let doubleDirty = false;
    Object.keys(nextProps.fields).forEach(key => {
      if (nextProps.fields[key].value !== this.props.fields[key].value) {
        doubleDirty = true;
      }
    });
    if (doubleDirty) {
      nextProps.handleSubmit();
    }
  }
}

2。通过onChange 处理程序在RadioForm 上调用submit

erikras proposes this here. 但它对我不起作用,因为它会跳过验证。

<input // ...
       onChange={(event) => {
          radioField.handleChange(event); // update redux state
          this.submit({ myField: event.target.value });
       }} />

我认为 Bitaru (same thread) 在他的回复中试图说同样的话,但我不确定。为我调用 onSubmit 会导致异常 Uncaught TypeError: _this2.props.onSubmit is not a function

3.通过this.refs在表单上致电submit

这会导致表单实际提交,完全跳过 redux-form

每个人:How to trigger a form submit in child component with Redux?

<input // ...
       onChange={(event) => {
         radioField.onChange(event);
         this.refs.radioForm.submit();
       }} />

【问题讨论】:

标签: reactjs redux react-redux redux-form


【解决方案1】:

您是否尝试过添加隐藏的提交按钮

<input ref="submit" type="submit" style="display: none;"/>

单选按钮 onChange 会调用 refs.submit.click() ?

【讨论】:

    【解决方案2】:

    我认为你提到的第二种方法会起作用,如果你有一个字段级别的验证和访问错误和触及元状态。

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 2018-02-07
      • 2017-10-24
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多