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

时间:2017-06-19 12:44:43

标签: reactjs redux react-redux redux-form

我想知道如何将自定义标志传递给redux-form 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));
&#13;
&#13;
&#13;

带有2个按钮的条形组件:

&#13;
&#13;
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);
&#13;
&#13;
&#13;

如何知道如何在handleFormSubmit中点击哪个按钮?

1 个答案:

答案 0 :(得分:3)

您可以将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 {}

上面的示例基本上是一个抽象的按钮,只要您提供表单名称和redux-form函数,就会提交onSubmit表单。您还应该能够提供any other props that reduxForm eats。如果您需要加载指示等,您可以使用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);

上述两个例子都应该被视为伪代码,我不保证它们可以开箱即用。这个原则确实有效,我已经实施了几次。

希望这有帮助!