WrapperForm.jsx 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { Form, Button } from 'antd';
  4. import WrapperItem from './WrapperItem';
  5. const formItemLayout = {
  6. labelCol: {
  7. xs: { span: 24 },
  8. sm: { span: 8 },
  9. },
  10. wrapperCol: {
  11. xs: { span: 24 },
  12. sm: { span: 16 },
  13. },
  14. };
  15. class WrapperForm extends React.Component {
  16. constructor(props) {
  17. super(props);
  18. this.state = {}
  19. }
  20. handleSubmit = e => {
  21. e.preventDefault();
  22. this.props.form.validateFieldsAndScroll((err, values) => {
  23. if (err) {
  24. if (typeof this.props.onError === 'function') {
  25. typeof this.props.onError(err)
  26. } else {
  27. window.console.error(err)
  28. }
  29. } else {
  30. if (typeof this.props.onSubmit === 'function') {
  31. typeof this.props.onSubmit(values)
  32. }
  33. }
  34. });
  35. }
  36. handleCancel = e => {
  37. e.preventDefault();
  38. if (typeof this.props.onCancel === 'function') {
  39. typeof this.props.onCancel()
  40. }
  41. }
  42. renderDefaultAction = (submitBtn, cancelBtn) => {
  43. let FieldSubmit = null
  44. let FieldCancel = null
  45. if (submitBtn !== false) {
  46. FieldSubmit = <Button htmlType="submit" type="primary">提交</Button>
  47. }
  48. if (cancelBtn !== false) {
  49. FieldCancel = <Button htmlType="button" onClick={this.handleCancel} style={{ marginLeft: '48px' }}>取消</Button>
  50. }
  51. return FieldSubmit || FieldCancel ? <WrapperItem action render={<>{FieldSubmit}{FieldCancel}</>} /> : null
  52. }
  53. render () {
  54. const {fields, form, children, submitBtn, cancelBtn, ...formProps} = this.props;
  55. console.log('fields:', fields)
  56. const FeildItems = (fields || []).filter(x => x).map((props, inx) => (<WrapperItem key={inx} {...props} form={form} />))
  57. return (
  58. <Form {...formItemLayout} {...formProps} onSubmit={this.handleSubmit}>
  59. {FeildItems}
  60. {this.renderDefaultAction(submitBtn, cancelBtn)}
  61. {children}
  62. </Form>
  63. );
  64. }
  65. }
  66. WrapperForm.propTypes = {
  67. fields: PropTypes.array.isRequired
  68. }
  69. export default WrapperForm;