我在redux-form中有一组简单的单选按钮.我需要单选按钮组的onChange事件来触发表单的onSubmit事件.
原文链接:https://www.f2er.com/react/301038.html我正在使用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
kyleboyle的proposal here根本不起作用.当我从componentWillReceiveProps调用nextProps.handleSubmit时,我得到this familiar error,Uncaught错误:你必须传递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上的提交
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不是函数
3.通过this.refs调用表单上的提交
这导致表单实际提交,完全跳过redux-form
每:How to trigger a form submit in child component with Redux?
<input // ... onChange={(event) => { radioField.onChange(event); this.refs.radioForm.submit(); }} />