在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
kyleboyle的提议根本行不通。当我从componentWillReceiveProps
调用nextProps.handleSubmit
时,我得到了这个熟悉的错误,Uncaught 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在这里提出了这个。但是它不适合我,因为它会跳过验证。
<input // ...
onChange={(event) => {
radioField.handleChange(event); // update redux state
this.submit({ myField: event.target.value });
}} />
我认为Bitaru(同一线程)试图在他的回答中说同样的事情,但我不确定。为我调用onSubmit
会导致Uncaught TypeError: _this2.props.onSubmit is not a function
3。通过this.refs
submit
这会导致表单实际提交,完全跳过redux-form
Per:如何用Redux触发子组件中的表单提交?
<input // ...
onChange={(event) => {
radioField.onChange(event);
this.refs.radioForm.submit();
}} />
有没有尝试添加一个隐藏的提交按钮
<input ref="submit" type="submit" style="display: none;"/>
和单选按钮onChange将调用ref .submit.click() ?
我认为你提到的第二种方法是可行的,如果你有一个字段级验证和访问错误和触摸元状态