# 对话框

- 页面: https://jiguang132.com/zh/resources/ant-design/docs/modal
- 资源: Ant Design (https://jiguang132.com/zh/resources/ant-design.md)
- 全部指南: https://jiguang132.com/zh/resources/ant-design/docs.md

展示一个对话框，提供标题、内容区、操作区。


## 何时使用 {#when-to-use}

需要用户处理事务，又不希望跳转页面以致打断工作流程时，可以使用 `Modal` 在当前页面正中打开一个浮层，承载相应的操作。

另外当需要一个简洁的确认框询问用户时，可以使用 [`App.useApp`](/components/app/) 封装的语法糖方法。

## 代码演示 {#examples}


- 基本 · `basic`
- 异步关闭 · `async`
- 自定义页脚 · `footer`
- 遮罩 · `mask`
- 加载中 · `loading`
- 自定义页脚渲染函数 · `footer-render`
- 使用 hooks 获得上下文 · `hooks`
- 国际化 · `locale`
- 手动更新和移除 · `manual`
- 自定义位置 · `position`

- 自定义页脚按钮属性 · `button-props`
- 自定义渲染对话框 · `modal-render`
- 自定义模态的宽度 · `width`
- 静态方法 · `static-info`
- 静态确认对话框 · `confirm`
- 销毁确认对话框 · `confirm-router`
- 自定义语义结构的样式和类 · `style-class`






## API

通用属性参考：[通用属性](#jguang-common-props)

| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| afterClose | Modal 完全关闭后的回调 | function | - |  | × |
| cancelButtonProps | cancel 按钮 props | [ButtonProps](/components/button#api) | - |  | 6.0.0 |
| cancelText | 取消按钮文字 | ReactNode | `取消` |  | × |
| centered | 垂直居中展示 Modal | boolean | false |  | 5.24.0 |
| classNames | 用于自定义 Modal 组件内部各语义化结构的 class，支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - |  | 5.10.0 |
| closable | 是否显示右上角的关闭按钮 | boolean \| [ClosableType](#closabletype) | true | - | 5.16.0 |
| closeIcon | 自定义关闭图标。5.7.0：设置为 `null` 或 `false` 时隐藏关闭按钮 | ReactNode | &lt;CloseOutlined /> |  | 5.14.0 |
| confirmLoading | 确定按钮 loading | boolean | false |  | × |
| ~~destroyOnClose~~ | 关闭时销毁 Modal 里的子元素 | boolean | false |  | × |
| destroyOnHidden | 关闭时销毁 Modal 里的子元素 | boolean | false | 5.25.0 | × |
| ~~focusTriggerAfterClose~~ | 对话框关闭后是否需要聚焦触发元素。请使用 `focusable.focusTriggerAfterClose` 替代 | boolean | true | 4.9.0 | × |
| footer | 底部内容，当不需要默认底部按钮时，可以设为 `footer={null}` | ReactNode \| (originNode: ReactNode, extra: { OkBtn: React.FC, CancelBtn: React.FC }) => ReactNode | (确定取消按钮) | renderFunction: 5.9.0 | × |
| forceRender | 强制渲染 Modal | boolean | false |  | × |
| focusable | 对话框内焦点管理的配置 | `{ trap?: boolean, focusTriggerAfterClose?: boolean }` | - | 6.2.0 | 6.4.0 |
| getContainer | 指定 Modal 挂载的节点，但依旧为全屏展示，`false` 为挂载在当前位置 | HTMLElement \| () => HTMLElement \| Selectors \| false | document.body |  | × |
| keyboard | 是否支持键盘 esc 关闭 | boolean | true |  | × |
| mask | 遮罩效果 | boolean \| `{enabled?: boolean, blur?: boolean, closable?: boolean}` | true | mask.closable: 6.3.0 | 6.0.0，mask.closable: 6.3.0 |
| ~~maskClosable~~ | 点击蒙层是否允许关闭。请使用 `mask.closable` 替代。 | boolean | true | - | × |
| modalRender | 自定义渲染对话框 | (node: ReactNode) => ReactNode | - | 4.7.0 | × |
| okButtonProps | ok 按钮 props | [ButtonProps](/components/button#api) | - |  | 6.0.0 |
| okText | 确认按钮文字 | ReactNode | `确定` |  | × |
| okType | 确认按钮类型 | string | `primary` |  | × |
| style | 可用于设置浮层的样式，调整浮层位置等 | CSSProperties | - |  | 5.7.0 |
| styles | 用于自定义 Modal 组件内部各语义化结构的行内 style，支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - |  | 5.10.0 |
| loading | 显示骨架屏 | boolean |  | 5.18.0 | × |
| scrollLock | 弹窗打开时是否锁定body滚动 | boolean | true | 6.5.0 | × |
| title | 标题 | ReactNode | - |  | × |
| open | 对话框是否可见 | boolean | false |  | × |
| width | 宽度 | string \| number \| [Breakpoint](/components/grid#col) | 520 | Breakpoint: 5.23.0 | × |
| wrapClassName | 对话框外层容器的类名 | string | - |  | × |
| zIndex | 设置 Modal 的 `z-index` | number | 1000 |  | × |
| onCancel | 点击遮罩层或右上角叉或取消按钮的回调 | function(e) | - |  | × |
| onOk | 点击确定回调 | function(e) | - |  | × |
| afterOpenChange | 打开和关闭 Modal 时动画结束后的回调 | (open: boolean) => void | - | 5.4.0 | × |

#### 注意 {#note}

- `<Modal />` 默认关闭后状态不会自动清空，如果希望每次打开都是新内容，请设置 `destroyOnHidden`。
- `<Modal />` 和 Form 一起配合使用时，设置 `destroyOnHidden` 也不会在 Modal 关闭时销毁表单字段数据，需要设置 `<Form preserve={false} />`。
- `Modal.method()` RTL 模式仅支持 hooks 用法。

### Modal.method()

包括：

- `Modal.info`
- `Modal.success`
- `Modal.error`
- `Modal.warning`
- `Modal.confirm`

以上均为一个函数，参数为 object，具体属性如下：

| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| afterClose | Modal 完全关闭后的回调 | function | - | 4.9.0 |
| ~~autoFocusButton~~ | 指定自动获得焦点的按钮。请使用 `focusable.autoFocusButton` 替代 | null \| `ok` \| `cancel` | `ok` |  |
| cancelButtonProps | cancel 按钮 props | [ButtonProps](/components/button#api) | - |  |
| cancelText | 设置 Modal.confirm 取消按钮文字 | string | `取消` |  |
| centered | 垂直居中展示 Modal | boolean | false |  |
| className | 容器类名 | string | - |  |
| closable | 是否显示右上角的关闭按钮 | boolean \| [ClosableType](#closabletype) | false | - |
| closeIcon | 自定义关闭图标 | ReactNode | undefined | 4.9.0 |
| content | 内容 | ReactNode | - |  |
| focusable.autoFocusButton | 指定自动获得焦点的按钮 | null \| `ok` \| `cancel` | `ok` | 6.2.0 |
| footer | 底部内容，当不需要默认底部按钮时，可以设为 `footer: null` | ReactNode \| (originNode: ReactNode, extra: { OkBtn: React.FC, CancelBtn: React.FC }) => ReactNode | - | renderFunction: 5.9.0 |
| getContainer | 指定 Modal 挂载的 HTML 节点，false 为挂载在当前 dom | HTMLElement \| () => HTMLElement \| Selectors \| false | document.body |  |
| icon | 自定义图标 | ReactNode | &lt;ExclamationCircleFilled /> |  |
| keyboard | 是否支持键盘 esc 关闭 | boolean | true |  |
| mask | 遮罩效果 | boolean \| `{enabled?: boolean, blur?: boolean, closable?: boolean}` | true |  |
| ~~maskClosable~~ | 点击蒙层是否允许关闭。请使用 `mask.closable` 替代。 | boolean | false | - |
| scrollLock | 弹窗打开时是否锁定body滚动 | boolean | true | 6.5.0 |
| okButtonProps | ok 按钮 props | [ButtonProps](/components/button#api) | - |  |
| okText | 确认按钮文字 | string | `确定` |  |
| okType | 确认按钮类型 | string | `primary` |  |
| style | 可用于设置浮层的样式，调整浮层位置等 | CSSProperties | - |  |
| title | 标题 | ReactNode | - |  |
| width | 宽度 | string \| number | 416 |  |
| wrapClassName | 对话框外层容器的类名 | string | - | 4.18.0 |
| zIndex | 设置 Modal 的 `z-index` | number | 1000 |  |
| onCancel | 点击取消回调，参数为关闭函数，若返回 promise 时 resolve 为正常关闭, reject 为不关闭 | function(close) | - |  |
| onOk | 点击确定回调，参数为关闭函数，若返回 promise 时 resolve 为正常关闭, reject 为不关闭 | function(close) | - |  |

以上函数调用后，会返回一个引用，可以通过该引用更新和关闭弹窗。

### ClosableType

| 参数       | 说明                   | 类型      | 默认值    | 版本 |
| ---------- | ---------------------- | --------- | --------- | ---- |
| afterClose | Modal 完全关闭后的回调 | function  | -         | -    |
| closeIcon  | 自定义关闭图标         | ReactNode | undefined | -    |
| disabled   | 关闭图标是否禁用       | boolean   | false     | -    |
| onClose    | 弹窗关闭即时调用       | Function  | undefined | -    |

```jsx
const modal = Modal.info();

modal.update({
  title: '修改的标题',
  content: '修改的内容',
});

// 在 4.8.0 或更高版本中，可以通过传入函数的方式更新弹窗
modal.update((prevConfig) => ({
  ...prevConfig,
  title: `${prevConfig.title}（新）`,
}));

modal.destroy();
```

- `Modal.destroyAll`

使用 `Modal.destroyAll()` 可以销毁弹出的确认窗（即上述的 `Modal.info`、`Modal.success`、`Modal.error`、`Modal.warning`、`Modal.confirm`）。通常用于路由监听当中，处理路由前进、后退不能销毁确认对话框的问题，而不用各处去使用实例的返回值进行关闭（`modal.destroy()` 适用于主动关闭，而不是路由这样被动关闭）

```jsx
import { browserHistory } from 'react-router';

// router change
browserHistory.listen(() => {
  Modal.destroyAll();
});
```

### Modal.useModal()

当你需要使用 Context 时，可以通过 `Modal.useModal` 创建一个 `contextHolder` 插入子节点中。通过 hooks 创建的临时 Modal 将会得到 `contextHolder` 所在位置的所有上下文。创建的 `modal` 对象拥有与 [`Modal.method`](#modalmethod) 相同的创建通知方法。

```jsx
const [modal, contextHolder] = Modal.useModal();

React.useEffect(() => {
  modal.confirm({
    // ...
  });
}, []);

return <div>{contextHolder}</div>;
```

`modal.confirm` 返回方法：

- `destroy`：销毁当前窗口
- `update`：更新当前窗口
- `then`：Promise 链式调用，支持 `await` 操作。该方法为 Hooks 仅有

```tsx
//点击 `onOk` 时返回 `true`，点击 `onCancel` 时返回 `false`
const confirmed = await modal.confirm({ ... });
```

## Semantic DOM

| 语义节点 | 原生说明 | 版本 |
| --- | --- | --- |
| `root` | 根元素，包含相对定位、顶部位置、宽度、最大宽度、外边距、底部内边距等模态框容器的基础布局样式 | 6.0.0 |
| `mask` | 遮罩层元素，包含固定定位、层级、背景色、动画过渡等遮罩层的样式 | 5.13.0 |
| `container` | Modal 容器元素，包含相对定位、背景色、背景裁剪、边框、圆角、阴影、指针事件、内边距等模态框主体样式 | 6.0.0 |
| `wrapper` | 包裹层元素，一般用于动画容器，包含动画和过渡效果的样式 | 5.13.0 |
| `header` | 头部元素，包含头部内边距、下边框等头部区域样式 | 5.13.0 |
| `title` | 标题元素，包含外边距、颜色、字体权重、字体大小、行高、文字换行等标题文字样式 | 6.0.0 |
| `body` | 内容元素，包含内容区域的背景色、内边距等内容展示样式 | 5.13.0 |
| `footer` | 底部元素，包含底部的背景色、内边距、上边框、圆角等底部区域样式 | 5.13.0 |
| `close` | 预览关闭按钮元素，设置按钮的基础样式 | 6.4.0 |

语义说明来源: `vendor/components/modal/demo/_semantic.tsx`

## 主题变量（Design Token）{#design-token}

类型、继承关系和原生令牌声明保持固定源码原文；默认值由原生主题计算，并可能受 ConfigProvider 覆盖。本表不伪造静态默认值。

| 令牌 | 类型 | 原生说明 |
| --- | --- | --- |
| `headerBg` | `string` | 顶部背景色 |
| `titleLineHeight` | `number \| string` | 标题行高 |
| `titleFontSize` | `number \| string` | 标题字体大小 |
| `titleColor` | `string` | 标题字体颜色 |
| `contentBg` | `string` | 内容区域背景色 |
| `footerBg` | `string` | 底部区域背景色 |
| `contentPadding` | `number \| string` | 见原生声明及继承类型 |
| `headerPadding` | `string \| number` | 见原生声明及继承类型 |
| `headerBorderBottom` | `string` | 见原生声明及继承类型 |
| `headerMarginBottom` | `number` | 见原生声明及继承类型 |
| `bodyPadding` | `number` | 见原生声明及继承类型 |
| `footerPadding` | `string \| number` | 见原生声明及继承类型 |
| `footerBorderTop` | `string` | 见原生声明及继承类型 |
| `footerBorderRadius` | `string \| number` | 见原生声明及继承类型 |
| `footerMarginTop` | `string \| number` | 见原生声明及继承类型 |
| `confirmBodyPadding` | `string \| number` | 见原生声明及继承类型 |
| `confirmIconMarginInlineEnd` | `string \| number` | 见原生声明及继承类型 |
| `confirmBtnsMarginTop` | `string \| number` | 见原生声明及继承类型 |

声明来源: `vendor/components/modal/style/index.ts`

```ts
import type React from 'react';

import type { CSSObject } from '@ant-design/cssinjs';

import { unit } from '@ant-design/cssinjs';

import { getMediaSize } from '../../grid/style';

import { genFocusOutline, genFocusStyle, resetComponent } from '../../style';

import { initFadeMotion, initZoomMotion } from '../../style/motion';

import type {
  AliasToken,
  FullToken,
  GenerateStyle,
  GenStyleFn,
  GlobalToken,
  TokenWithCommonCls,
} from '../../theme/internal';

import { genStyleHooks, mergeToken } from '../../theme/internal';

/** Component only token. Which will handle additional calculation of alias token */
export interface ComponentToken {
  // Component token here
  /**
   * @desc 顶部背景色
   * @descEN Background color of header
   */
  headerBg: string;
  /**
   * @desc 标题行高
   * @descEN Line height of title
   */
  titleLineHeight: number | string;
  /**
   * @desc 标题字体大小
   * @descEN Font size of title
   */
  titleFontSize: number | string;
  /**
   * @desc 标题字体颜色
   * @descEN Font color of title
   */
  titleColor: string;
  /**
   * @desc 内容区域背景色
   * @descEN Background color of content
   */
  contentBg: string;
  /**
   * @desc 底部区域背景色
   * @descEN Background color of footer
   */
  footerBg: string;

  /** @internal */
  contentPadding: number | string;
  /** @internal */
  headerPadding: string | number;
  /** @internal */
  headerBorderBottom: string;
  /** @internal */
  headerMarginBottom: number;
  /** @internal */
  bodyPadding: number;
  /** @internal */
  footerPadding: string | number;
  /** @internal */
  footerBorderTop: string;
  /** @internal */
  footerBorderRadius: string | number;
  /** @internal */
  footerMarginTop: string | number;
  /** @internal */
  confirmBodyPadding: string | number;
  /** @internal */
  confirmIconMarginInlineEnd: string | number;
  /** @internal */
  confirmBtnsMarginTop: string | number;
}

/**
 * @desc Modal 组件的 Token
 * @descEN Token for Modal component
 */
export interface ModalToken extends FullToken<'Modal'> {
  /**
   * @desc 模态框头部高度
   * @descEN Height of modal header
   */
  modalHeaderHeight: number | string;
  /**
   * @desc 模态框底部边框颜色
   * @descEN Border color of modal footer
   */
  modalFooterBorderColorSplit: string;
  /**
   * @desc 模态框底部边框样式
   * @descEN Border style of modal footer
   */
  modalFooterBorderStyle: string;
  /**
   * @desc 模态框底部边框宽度
   * @descEN Border width of modal footer
   */
  modalFooterBorderWidth: number | string;
  /**
   * @desc 模态框关闭图标颜色
   * @descEN Color of modal close icon
   */
  modalCloseIconColor: string;
  /**
   * @desc 模态框关闭图标悬停颜色
   * @descEN Hover color of modal close icon
   */
  modalCloseIconHoverColor: string;
  /**
   * @desc 模态框关闭按钮尺寸
   * @descEN Size of modal close button
   */
  modalCloseBtnSize: number | string;
  /**
   * @desc 模态框确认图标尺寸
   * @descEN Size of modal confirm icon
   */
  modalConfirmIconSize: number | string;
  /**
   * @desc 模态框标题高度
   * @descEN Height of modal title
   */
  modalTitleHeight: number | string;
}
```

## FAQ

### 为什么 Modal 关闭时，内容不会更新？ {#faq-content-not-update}

Modal 在关闭时会将内容进行 memo 从而避免关闭过程中的内容跳跃。也因此如果你在配合使用 Form 有关闭时重置 `initialValues` 的操作，请通过在 effect 中调用 `resetFields` 来重置。

### 为什么 Modal 方法不能获取 context、redux 的内容和 ConfigProvider `locale/prefixCls/theme` 等配置？ {#faq-context-redux}

直接调用 Modal 方法，antd 会通过 `ReactDOM.render` 动态创建新的 React 实体。其 context 与当前代码所在 context 并不相同，因而无法获取 context 信息。

当你需要 context 信息（例如 ConfigProvider 配置的内容）时，可以通过 `Modal.useModal` 方法会返回 `modal` 实体以及 `contextHolder` 节点。将其插入到你需要获取 context 位置即可：

```tsx
const [modal, contextHolder] = Modal.useModal();

return (
  <Context1.Provider value="Ant">
    {/* contextHolder 在 Context1 内，它可以获得 Context1 的 context */}
    {contextHolder}
    <Context2.Provider value="Design">
      {/* contextHolder 在 Context2 外，因而不会获得 Context2 的 context */}
    </Context2.Provider>
  </Context1.Provider>
);
```

**异同**：通过 hooks 创建的 `contextHolder` 必须插入到子元素节点中才会生效，当你不需要上下文信息时请直接调用。

> 可通过 [App 包裹组件](/components/app) 简化 `useModal` 等方法需要手动植入 contextHolder 的问题。

### 静态方法如何设置 prefixCls ？ {#faq-set-prefix-cls}

你可以通过 [`ConfigProvider.config`](/components/config-provider#config) 进行设置。


## 原生通用属性 {#jguang-common-props}


> Tips: 以下通用属性适用于 antd 大部分组件，不支持的组件会单独说明。

| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| style | 自定义样式 | CSSProperties | - |
| className | 自定义类名 | string | - |
| rootClassName | 添加在组件最外层的 className | string | - |
| autoFocus | 自动获取焦点，仅对表单类、链接、交互容器等可聚焦元素生效 | boolean | false |


## 安装并复现示例

```bash
npm install antd@6.6.5 @ant-design/icons@6.3.4 dayjs@1.11.23
```

使用 ConfigProvider 和原生 App，并单独配置 dayjs 语言。每个示例在查看代码中列出完整源码文件和额外固定依赖。示例名称用于选择演示，不是组件通用属性。主题、语言与 SSR 初始化见资源安装指南。

## 原生类型参考

源码查看器包含未修改的原生实现和以下声明文件，继承类型仍位于原生包中。代码中的英文注释保留为源码参考。

- `vendor/components/modal/ConfirmDialog.tsx`
- `vendor/components/modal/Modal.tsx`
- `vendor/components/modal/PurePanel.tsx`
- `vendor/components/modal/components/ConfirmCancelBtn.tsx`
- `vendor/components/modal/components/ConfirmOkBtn.tsx`
- `vendor/components/modal/components/NormalCancelBtn.tsx`
- `vendor/components/modal/components/NormalOkBtn.tsx`
- `vendor/components/modal/confirm.tsx`
- `vendor/components/modal/context.ts`
- `vendor/components/modal/index.tsx`
- `vendor/components/modal/interface.ts`
- `vendor/components/modal/shared.tsx`
- `vendor/components/modal/style/index.ts`
- `vendor/components/modal/useModal/HookModal.tsx`
- `vendor/components/modal/useModal/index.tsx`

## 来源与许可

https://github.com/ant-design/ant-design/tree/4a39f54842eade4e565ab336ef6097cd7e723cdd

保留原生中英文正文与可执行示例；官网专用的嵌入章节和令牌表格在本地展开。Ant Design 使用 MIT 许可，另列依赖的许可证也需保留。上传预览禁止向外发起请求，不提供后端服务。

---

JGuang 全部资源索引: https://jiguang132.com/llms.txt
