index.tsx 1.4 KB
import React, { useEffect } from 'react';
import { Modal, ModalProps } from 'antd';
import { FormProvider } from '@formily/react';
import { createForm } from '@formily/core';

interface Props extends ModalProps {
  handleOk?: (values: { [props: string]: string }, e: React.MouseEvent<HTMLButtonElement>) => void;
  handleCancel?: (e: React.MouseEvent<HTMLButtonElement>) => void;
  initialValues?: { props?: string };
  open: boolean;
}

const FormModal: React.FC<Props> = (props) => {
  const form = createForm();
  const {
    initialValues,
    title = '我是弹框标题',
    handleOk,
    handleCancel,
    children = [],
    open,
    ...args
  } = props;
  const items = React.Children.toArray(children);

  useEffect(() => {
    form.setInitialValues(initialValues);
  });

  const onOK = (e: React.MouseEvent<HTMLButtonElement>) => {
    if (handleOk) {
      form.submit().then((values: any) => {
        handleOk(values, e);
      });

      return;
    }
  };

  const onCancel = (e: React.MouseEvent<HTMLButtonElement>) => {
    if (handleCancel) {
      handleCancel(e);

      return;
    }
  };

  return (
    <Modal
      title={title}
      open={open}
      onOk={onOK}
      onCancel={onCancel}
      maskClosable={false}
      centered
      {...args}
      getContainer={false}
    >
      <FormProvider form={form}>{React.Children.map(items, (item: any) => item)}</FormProvider>
    </Modal>
  );
};

export default FormModal;