带有自定义标志的 Redux-Form 6.8.0 远程提交

Redux-Form 6.8.0 remote submit with custom flag

我想知道如何将自定义标志传递给 redux 形式 onSubmit 函数。我的场景是我在 redux 表单之外有 2 个保存按钮(都调用不同的 API 请求)所以我使用远程提交方法。

表单组件:

function handleFormSubmit(data) {
  // I need to distinguish here which button was clicked
}

class FormComponent extends React.Component {
  
  render() {
    return (
      <form onSubmit={this.props.handleSubmit}>
        ...
      </form>
    );
  }
}

export default connect(mapStateToProps, {
})(reduxForm({
  form: 'MyForm',
  onSubmit: handleFormSubmit,
})(FormComponent));

带有 2 个按钮的栏组件:

import React from 'react';

class BarComponent extends React.Component {
  props: Props;


  render() {
    return (
      <div>
        <button onChange={this.props.submit('MyForm')}>Save</button>
        <button onChange={this.props.submit('MyForm')}>Save as new version</button>
      </div>
    );
  }
}

export default connect(mapStateToProps, {
  submit
})(BarComponent);

有什么想法可以知道 handleFormSubmit 中哪个按钮被点击了吗?

您可以将每个按钮包装在一个 reduxForm 中,与您的主窗体具有相同的 name,并为两者实现不同的 onSubmit 逻辑。更好的是,你可以很好地抽象出来:

// component code (take with a grain on pseudo-code salt)
export class SubmitButton extends Component {

  render() {
    const { children, handleSubmit } = this.props

    return (
      <form onSubmit={ handleSubmit }>
        <button type="submit">{ children }</button>
      </form>
    )
  }

}

@reduxForm()
export default SubmitButtonContainer extends SubmitButton {}

上面的例子基本上是一个抽象的按钮,只要您提供表单名称和 onSubmit 函数,它就会提交一个 redux-form 表单。您还应该能够提供 any other props that reduxForm eats. If you need loading indication etc, you can just use the props that come with wrapping a component with reduxForm.

然后您可以像下面这样使用它来实现绑定到不同按钮的自定义提交逻辑:

// usage code (again more pseudo-code salts with this one)
import React from 'react';
import SubmitButton from 'path/to/SubmitButton'

class BarComponent extends React.Component {
  props: Props;

  onSave() {
    // do the regular save logic here
  }

  onSaveAsNewVersion() {
    // do the other save logic here
  }

  render() {
    return (
      <div>
        <SubmitButton form="MyFormName" onSubmit={ this.onSave }>Save</button>
        <SubmitButton form="MyFormName" onSubmit={ this.onSaveAsNewVersion }>Save as new version</button>
      </div>
    );
  }
}

export default connect(mapStateToProps, {
  submit
})(BarComponent);

上面的两个例子都应该被视为伪代码,我不保证它们会开箱即用。这个原理确实有效,我已经实现了几次。

希望对您有所帮助!