【发布时间】: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 error、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 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();
}} />
【问题讨论】:
-
当你像这样导出 RadioForm 时应该使用 onSubmit 函数 `export default reduxForm({ form: 'remoteSubmit', // 这个表单的唯一标识符 onSubmit: submit // 必须传递提交函数到 onSubmit })(RemoteSubmitForm)' redux-form.com/6.6.3/examples/remotesubmit
标签: reactjs redux react-redux redux-form