我在 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。从 RadioForm

上的 componentWillReceiveProps 调用 handleSubmit

凯尔博伊尔的 proposal here根本行不通。当我从 componentWillReceiveProps 调用 nextProps.handleSubmit 时,我得到 this familiar error , Uncaught Error :您必须向 handleSubmit() 传递一个 onSubmit 函数,或者将 onSubmit 作为 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

埃里克拉斯 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(); 
       }} /> 

请您参考如下方法:

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

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

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!