Redux Form:如何处理多个按钮? [英] Redux Form: How to handle multiple buttons?
问题描述
我正在尝试向 redux-form 添加第二个提交按钮.
两个按钮都应该发送一个保存数据的动作,但是根据按下的按钮,用户应该被路由到不同的页面.
所以我定义了一个处理程序,我将它作为 onSubmit
属性传递给表单.
但据我所知,只有表单 data 被传递给这个处理程序:
handleSubmit
注意:
要传递给 的函数或
.它将运行同步和异步验证,并且,如果表单有效,它将使用表单数据的内容调用
this.props.onSubmit(data)
.
我缺少的是一种将有关按下的按钮的信息(例如单击事件)传递给我的 onSubmit 处理程序的方法,以便我可以按预期进行保存和路由.
有很多方法可以做到这一点,但它们都涉及根据按下的按钮附加按钮数据.这是一个内联版本.
class Morpheus 扩展组件 {使成为() {const { handleSubmit } = this.props;返回 (<div>字段到这里<button onClick={handleSubmit(values =>this.props.onSubmit({...值,药丸:'蓝色'}))}>蓝色药丸</button><button onClick={handleSubmit(values =>this.props.onSubmit({...值,药丸:'红色'}))}>红色药丸</button>
);}}导出默认 reduxForm({形式:'morpheus'})(睡眠)
handleSubmit
处理所有验证检查和诸如此类的事情,如果一切都有效,它将使用表单值调用提供给它的函数.所以我们给它一个函数来附加额外的信息并调用onSubmit()
.
I am trying to add a second submit button to a redux-form.
Both buttons should dispatch an action that saves the data but depending on the button pressed the user should be routed to different pages.
So I defined a handler that I pass as onSubmit
prop to the form.
But as far as I can see only the form data is passed to this handler:
The docs on handleSubmit
note:
A function meant to be passed to
<form onSubmit={handleSubmit}>
or to<button onClick={handleSubmit}>
. It will run validation, both sync and async, and, if the form is valid, it will callthis.props.onSubmit(data)
with the contents of the form data.
What I am missing is a way to also pass the information about the button pressed (e.g. the click event) to my onSubmit handler, so that i can save and route as intended.
There are many ways to do this, but they all involve appending the button data depending on which button was pressed. Here's an inline version.
class Morpheus extends Component {
render() {
const { handleSubmit } = this.props;
return (
<div>
Fields go here
<button onClick={handleSubmit(values =>
this.props.onSubmit({
...values,
pill: 'blue'
}))}>Blue Pill</button>
<button onClick={handleSubmit(values =>
this.props.onSubmit({
...values,
pill: 'red'
}))}>Red Pill</button>
</div>
);
}
}
export default reduxForm({
form: 'morpheus'
})(Morpheus)
The handleSubmit
handles all the validation checking and whatnot, and if everything is valid, it will call the function given to it with the form values. So we give it a function that appends extra information and calls onSubmit()
.
这篇关于Redux Form:如何处理多个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!