Redux Form:如何处理多个按钮? [英] Redux Form: How to handle multiple buttons?

查看:41
本文介绍了Redux Form:如何处理多个按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向 redux-form 添加第二个提交按钮.

两个按钮都应该发送一个保存数据的动作,但是根据按下的按钮,用户应该被路由到不同的页面.

所以我定义了一个处理程序,我将它作为 onSubmit 属性传递给表单.

但据我所知,只有表单 data 被传递给这个处理程序:

handleSubmit 注意:

<块引用>

要传递给

的函数或

);}}导出默认 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 call this.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆