redux-form:在输入onChange

时间:2016-08-11 17:00:47

标签: reactjs redux react-redux redux-form

我在redux-form中有一组简单的单选按钮。我需要单选按钮组的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。从handleSubmit

上的componentWillReceiveProps致电RadioForm

kyleboyle的proposal here根本行不通。当我从nextProps.handleSubmit致电componentWillReceiveProps时,我得到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。从submit处理程序

致电RadioForm上的onChange

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。通过submit

在表单上致电this.refs

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

Per:How to trigger a form submit in child component with Redux?

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

2 个答案:

答案 0 :(得分:0)

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

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

并且单选按钮onChange将调用refs.submit.click()?

答案 1 :(得分:0)

我认为,如果您具有字段级别的验证并可以访问错误和触及的元状态,那么您提到的第二种方法将行得通。

相关问题