React ModalForm自定义类名 ClassName

145 阅读2分钟

一般在使用Modal的时候某些情况下需要自定义ModalForm的样式,一般的情况是直接加className,但是这个Modal就不是。

首先需要理解的是:ModalForm其实就是ModalForm合在一起的;外层是Modal,既然想要控制ModalForm的样式,则先来了解一下ModalForm的结构:

image.png 由上图可见,ModalForm的结构和Modal一样,整个页面的class是ant-modal-content,在DevTools对话框中选中对话框,可以看到整个Modal是由header、body、footer,还有右上角的叉叉按钮都成以及其对应的类名; 这里如果需要自定义一个类名,则需要使用 wrapClassName这个关键字来进行自定义

image.png 因为我这里需要全局的ModalForm都需要这个样式,因此我在其他文件重新定义了相关的样式,如下:

import { FormProps } from '@ant-design/pro-components';
import { ModalProps } from 'antd';

export const uppModalFormLayout: Omit<FormProps, 'onFinish' | 'title'> & { width: number } = {
  width: 600,
  colon: false,
  layout: 'horizontal',
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

export const udpModalFormProps: Omit<ModalProps, 'visible'> = {
  styles: {
    header: {
      fontSize: '16px',
      color: '#5C6280',
      textAlign: 'center',
      fontWeight: '400',
      padding: '10px',
      boxShadow: 'inset 0 -1px 0 0 #E6E6E6',
    },
    body: {
      padding: '20px',
      boxShadow: 'inset 0 -1px 0 0 #E6E6E6',
    },
    footer: {
      paddingTop: '10px',
    },
  },
  wrapClassName: 'container',
};

如下使用即可

import {
  udpModalFormProps,
  uppModalFormLayout,
} from '@/index.tsx';

<ModalForm
        form={form}
        title="创建表单"
        {...uppModalFormLayout}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            modal.hide();
          },
          ...udpModalFormProps,
        }}
        onFinish={async () => {
          await form.validateFields();
          handleStlConfigSubmit(form.getFieldsValue());
          modal.remove();
          return true;
        }}
        open={modal.visible}>
        <Form.Item<FieldType>
          label="Username"
          name="username"
          rules={[{ required: true, message: 'Please input your username!' }]}>
          <Input />
        </Form.Item>
      </ModalForm>

为什么要自定义类别呢?因为某些情况下需要兼容Chrome75版本的浏览器,由于ModalForm自带的确定,取消按钮的间距是由属性gap控制的,但是这个属性在Chrome75里面是不能识别的如下图所示,两个按钮就会挨在一起, image.png

此时解决这个的一种方案是自定义一个类名来控制这两个按钮的间距,解决方案如下:在上述的wrapClassName定义的类名为"container",如下定义

.container {
  .ant-modal .ant-modal-footer > div + div {
    display: flex !important;
    margin-bottom: -16px !important;
    margin-right: -16px !important;
  }
  .ant-modal-footer button {
    margin-right: 16px !important;
    margin-bottom: 16px !important;
  }
}

最终在Chrome75效果如下:

image.png