redux-form:访问 handleSubmit 上的状态和表单值

redux-form: Accessing state and form-values on handleSubmit

我有以下 redux-form (6.5.0) 源代码:

class MyForm extends Component {

 handleSubmit() {
   console.log("Inside the handleSubmit of the MyForm Component where state is accessible", this.state.MyStateElement);
 }

 function render() {
  return (
    <<<< CHOICE 1: >>>> 
      <form onSubmit={handleSubmit(this.handleSubmit.bind(this))} >

    <<<< CHOICE 2: >>>> 
      <form onSubmit={handleSubmit(submit)}>

    {someFields}
   </form>
  );
 }
}

function submit(values) {
 console.log("submit function outside the MyForm Component where form values are accessible but the State is NOT accessible", values);
 // values correspond to every checkbox, radio button inside MyForm
}

有一个 MyForm 组件。它内部有一个 redux-form。现在在 react 组件中定义了一个 handleSubmit() 函数。在 React 组件之外定义了一个 submit() 函数。现在我可以为表单标记启用 CHOICE 1 或 CHOICE 2 定义。如果我启用第一个,则会调用反应组件内的 handleSubmit。在这里,我可以访问 this.state 但无法访问表单内的各个字段(除非我可以手动将每个字段映射到全局状态,而我无法为数十个字段明确执行此操作我有)。如果我启用 CHOICE 2,所有字段的值都会正确地进入 submit 函数。但是我无法访问 submit 函数中的 this.state

我的问题是:有没有办法在 handleSubmit/submit 函数中获取字段值以及 this.state

好的,我找到了解决方案(但不确定这是否是最好的)。我只需要将值参数添加到 handleSubmit 函数。所以更新的来源将是:

class MyForm extends Component {

 handleSubmit(values) {
   console.log("State:", this.state.MyStateElement);
   console.log("Form values:", values);
 }

 function render() {
  return (
   <form onSubmit={handleSubmit(this.handleSubmit.bind(this))} >
    {someFields}
   </form>
  );
 }
}

另一种解决方案是...

1) 当您使用 reduxForm 包装表单组件时,您指定了 onSubmit 选项。

class myForm extends React.Component {}

export default reduxForm({
    form: 'myForm',
    onSubmit: function(values) { console.log('hello', values) }
})(myForm);

2) 此函数在组件内部可用 this.props.handleSubmit,因此您仍然可以编写自己的提交处理程序并在其中调用 this.props.handleSubmit

class myForm extends React.Component {
  myOwnSubmitHanlder() {
    console.log('hello', this.state);
    this.props.handleSubmit()
  }
  
  render() {
    return (
      <form onSubmit={this.myOwnSubmitHanlder}></form>
    )
  }
}