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

export interface FormModalProps 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<FormModalProps> = ({
  initialValues,
  title = '我是弹框标题',
  handleOk,
  handleCancel,
  children,
  open,
  ...args
}) => {
  const form = createForm();

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

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

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

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

export default FormModal;