Redux Form: How to handle multiple buttons?

爱⌒轻易说出口 提交于 2019-11-28 23:19:09

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().

@mibbit onSubmit is a function that you define (at least this is what the doc says: look the onSubmit method). This is for redux-form 7.x following example of @Erik R.

    class Morpheus extends Component {
    constructor(props) {
        super(props);

        this.state = {};
        this.onSubmit = this.onSubmit.bind(this);
    }

    onSubmit(values, pill) {
        // do magic here
    }

    render() {
        const {
            handleSubmit
        } = this.props;
        return ( <
            div >
            Fields go here <
            button onClick = {
                handleSubmit(values =>
                    this.onSubmit({
                        values,
                        pill: 'blue'
                    }))
            } > Blue Pill < /button> <
            button onClick = {
                handleSubmit(values =>
                    this.onSubmit({
                        values,
                        pill: 'red'
                    }))
            } > Red Pill < /button> <
            /div>
        );
    }
}

export default reduxForm({
    form: 'morpheus'
})(Morpheus)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!