> Leaf UI 0.17.3 · Package: @ifhover/leaf-ui · Source: c3221834f84f2f48481a2054026b713456f8e5dc
> Browser documentation: https://ifhover.github.io/leaf-ui/components/modal.html

> For AI agents: the complete documentation index is available at https://ifhover.github.io/leaf-ui/llms.txt, the full documentation bundle is available at https://ifhover.github.io/leaf-ui/llms-full.txt.

# Modal 弹窗

在独立弹窗中查看或编辑内容。

仅需确认或取消时使用 [Confirm](https://ifhover.github.io/leaf-ui/components/confirm.md)，希望在触发按钮旁确认时使用 [Popconfirm](https://ifhover.github.io/leaf-ui/components/popconfirm.md)。


## 基础用法

[](#)
使用 `type="submit"` 和表单 ID 关联默认确定按钮，保留原生校验。由表单的 `onSubmit` 更新 `open`。


编辑标题

basic.tsx

复制代码

```tsx lineNumbers file="../../src/examples/modal/basic.tsx"
import { Button, Form, FormField, Input, Modal } from '@ifhover/leaf-ui';
import { useId, useState } from 'react';

export function ModalBasic() {
  const [open, setOpen] = useState(false);
  const formId = useId();
  return (
    <>
      <Button onClick={() => setOpen(true)}>编辑标题</Button>
      <Modal
        open={open}
        title="编辑标题"
        confirmText="保存"
        onClose={() => setOpen(false)}
        confirmButtonProps={{ type: 'submit', form: formId }}
      >
        <Form
          id={formId}
          layout="vertical"
          onSubmit={(event) => {
            event.preventDefault();
            setOpen(false);
          }}
        >
          <FormField label="标题" required>
            <Input name="title" defaultValue="Leaf UI" />
          </FormField>
        </Form>
      </Modal>
    </>
  );
}
```

展开代码


## 示例

### 图标与说明

通过 `icon` 和 `description` 为弹窗补充图标与说明。标题和底部默认显示分隔线，通过 `divided={false}` 关闭。


重命名文件

description.tsx

复制代码

```tsx lineNumbers file="../../src/examples/modal/description.tsx"
import { Button, Form, FormField, Input, Modal } from '@ifhover/leaf-ui';
import { Pencil } from 'lucide-react';
import { useId, useState } from 'react';

export function ModalDescription() {
  const [open, setOpen] = useState(false);
  const formId = useId();
  return (
    <>
      <Button onClick={() => setOpen(true)}>重命名文件</Button>
      <Modal
        open={open}
        title="重命名文件"
        description="新名称会用于文件列表和下载。"
        icon={<Pencil />}
        confirmText="保存"
        onClose={() => setOpen(false)}
        confirmButtonProps={{ type: 'submit', form: formId }}
      >
        <Form
          id={formId}
          layout="vertical"
          onSubmit={(event) => {
            event.preventDefault();
            setOpen(false);
          }}
        >
          <FormField label="文件名" required>
            <Input name="filename" defaultValue="设计说明.md" />
          </FormField>
        </Form>
      </Modal>
    </>
  );
}
```

展开代码

### 自定义底部

函数形式的 `footer` 接收默认按钮，可保留其确认与取消逻辑并增加操作。自定义按钮间距由 `Space` 管理；`footer={null}` 隐藏底部。


自定义底部

footer.tsx

复制代码

```tsx lineNumbers file="../../src/examples/modal/footer.tsx"
import { Button, Modal, Paragraph, Space } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ModalFooter() {
  const [open, setOpen] = useState(false);
  const [details, setDetails] = useState(false);
  return (
    <>
      <Button onClick={() => setOpen(true)}>自定义底部</Button>
      <Modal
        open={open}
        title="草稿说明"
        onClose={() => setOpen(false)}
        footer={({ cancelButton, confirmButton }) => (
          <Space size="sm" wrap>
            <Button variant="text" onClick={() => setDetails(!details)}>
              {details ? '收起详情' : '查看详情'}
            </Button>
            {cancelButton}
            {confirmButton}
          </Space>
        )}
      >
        <Paragraph>新文档会保存为草稿，之后仍可修改内容。</Paragraph>
        {details && <Paragraph>草稿只对你可见，发布后才会与其他人共享。</Paragraph>}
      </Modal>
    </>
  );
}
```

展开代码

[](#)
### 关闭后销毁内容

默认在首次打开后保留内容。`destroyOnClose` 在关闭过渡结束后卸载内容，再次打开时非受控输入恢复初始值。`preserve` 优先于 `destroyOnClose`，而 `forceRender` 会保持内容挂载；组件外保存的受控状态仍需应用自行重置。


打开临时草稿

destroy.tsx

复制代码

```tsx lineNumbers file="../../src/examples/modal/destroy.tsx"
import { Button, Form, FormField, Input, Modal } from '@ifhover/leaf-ui';
import { useId, useState } from 'react';

export function ModalDestroy() {
  const [open, setOpen] = useState(false);
  const formId = useId();
  return (
    <>
      <Button onClick={() => setOpen(true)}>打开临时草稿</Button>
      <Modal
        open={open}
        title="临时草稿"
        destroyOnClose
        confirmText="完成"
        confirmButtonProps={{ type: 'submit', form: formId }}
        onClose={() => setOpen(false)}
      >
        <Form
          id={formId}
          layout="vertical"
          onSubmit={(event) => {
            event.preventDefault();
            setOpen(false);
          }}
        >
          <FormField label="草稿标题">
            <Input name="draft" defaultValue="新的草稿" />
          </FormField>
        </Form>
      </Modal>
    </>
  );
}
```

展开代码

### 初始焦点

默认聚焦弹窗中的第一个可聚焦控件，通过 `initialFocus` 可指定其他目标。关闭后默认恢复打开前的焦点，也可用 `returnFocus` 指定返回位置。


聚焦输入框

focus.tsx

复制代码

```tsx lineNumbers file="../../src/examples/modal/focus.tsx"
import { Button, FormField, Input, Modal } from '@ifhover/leaf-ui';
import { useRef, useState } from 'react';

export function ModalFocus() {
  const [open, setOpen] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  return (
    <>
      <Button onClick={() => setOpen(true)}>聚焦输入框</Button>
      <Modal open={open} title="编辑标题" initialFocus={inputRef} onClose={() => setOpen(false)}>
        <FormField layout="vertical" label="标题">
          <Input ref={inputRef} defaultValue="Leaf UI" />
        </FormField>
      </Modal>
    </>
  );
}
```

展开代码

### 异步提交

返回 Promise 可显示加载状态并阻止重复操作；等待期间，默认取消、关闭按钮、遮罩与 Escape 均不能关闭弹窗。`onConfirm` 成功后仍需应用更新 `open`，抛出错误则保留弹窗并显示错误信息。


异步保存标题已保存：Leaf UI

async.tsx

复制代码

```tsx lineNumbers file="../../src/examples/modal/async.tsx"
import { Button, FormField, Input, Modal, Space, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ModalAsync() {
  const [open, setOpen] = useState(false);
  const [draft, setDraft] = useState('Leaf UI');
  const [saved, setSaved] = useState('Leaf UI');
  const [saving, setSaving] = useState(false);
  return (
    <Space direction="vertical" align="start">
      <Button
        onClick={() => {
          setDraft(saved);
          setOpen(true);
        }}
      >
        异步保存标题
      </Button>
      <Text tone="muted" role="status">
        已保存：{saved}
      </Text>
      <Modal
        open={open}
        title="编辑标题"
        confirmText="保存"
        onClose={() => setOpen(false)}
        onConfirm={async () => {
          setSaving(true);
          try {
            await new Promise<void>((resolve) => setTimeout(resolve, 900));
            setSaved(draft);
            setOpen(false);
          } finally {
            setSaving(false);
          }
        }}
      >
        <FormField layout="vertical" label="标题">
          <Input
            value={draft}
            disabled={saving}
            onChange={(event) => setDraft(event.target.value)}
          />
        </FormField>
      </Modal>
    </Space>
  );
}
```

展开代码

### 标签页弹窗

通过 `tabs` 在标题下方或顶部嵌入线形标签页。标签栏固定在正文滚动区上方，即使设置 `divided={false}` 也会保留标签栏底部分割线；若仅将标签栏用于切换状态并把内容写在 Modal 的 `children` 中，可省略各项的 `children`。


项目配置

tabs.tsx

复制代码

```tsx lineNumbers file="../../src/examples/modal/tabs.tsx"
import { Button, Modal, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ModalTabs() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <Button onClick={() => setOpen(true)}>项目配置</Button>
      <Modal
        open={open}
        title="项目配置"
        divided={false}
        onClose={() => setOpen(false)}
        tabs={{
          items: [
            {
              key: 'general',
              label: '基本信息',
              children: <Text>在独立标签页中展示配置表单或详情。</Text>,
            },
            {
              key: 'members',
              label: '成员权限',
              children: <Text>标签栏固定在正文上方，内容超长时仅正文区滚动。</Text>,
            },
          ],
        }}
      />
    </>
  );
}
```

展开代码


## API

### Modal API

控制弹窗的显示状态、内容与底部操作。

没有 `title` 时，通过 `aria-label` 提供弹窗名称。

| 属性                   | 类型                                                                                     | 默认值     | 说明                                                                                                                                                                          |
| -------------------- | -------------------------------------------------------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open`               | `boolean`                                                                              | 必填      | 受控的打开状态，应用负责更新。                                                                                                                                                             |
| `title`              | `ReactNode`                                                                            | —       | 弹窗标题。                                                                                                                                                                       |
| `description`        | `ReactNode`                                                                            | —       | 补充说明。                                                                                                                                                                       |
| `tabs`               | [`ModalTabsProps`](#modaltabs-api)                                                     | —       | 内嵌标签页；无标题时替代标题栏，有标题时位于其下方；底部分割线始终保留。                                                                                                                                        |
| `onClose`            | `() => void`                                                                           | —       | 请求关闭，由应用更新 open                                                                                                                                                             |
| `onConfirm`          | `() => void \| Promise<void>`                                                          | —       | 默认确认按钮的操作，可返回 Promise；等待期间阻止重复确认和默认关闭。成功后应用仍须更新 open。                                                                                                                       |
| `onCancel`           | `() => void`                                                                           | —       | 取消按钮、关闭按钮、遮罩或 Escape 请求关闭时调用；省略时调用 onClose。                                                                                                                                 |
| `confirmText`        | `ReactNode`                                                                            | 语言默认值   | 默认确认按钮的内容，支持文本或 React 节点；为 `null` 或 `undefined` 时使用当前语言的 `common.confirm`（简体中文为“确定”，英文为“OK”）。对默认底部及 `footer` 函数接收的 `confirmButton` 生效，不影响自定义按钮。                             |
| `cancelText`         | `ReactNode`                                                                            | 语言默认值   | 默认取消按钮的内容，支持文本或 React 节点；为 `null` 或 `undefined` 时使用当前语言的 `common.cancel`（简体中文为“取消”，英文为“Cancel”）。对默认底部及 `footer` 函数接收的 `cancelButton` 生效，不影响自定义按钮；隐藏整个底部请设置 `footer={null}`。 |
| `confirmLoading`     | `boolean`                                                                              | `false` | 确认加载状态                                                                                                                                                                      |
| `confirmButtonProps` | [`ButtonProps`](https://ifhover.github.io/leaf-ui/components/button.md#button-api)     | —       | 定制默认按钮属性                                                                                                                                                                    |
| `cancelButtonProps`  | [`ButtonProps`](https://ifhover.github.io/leaf-ui/components/button.md#button-api)     | —       | 定制默认按钮属性                                                                                                                                                                    |
| `footer`             | `ReactNode \| ((actions: `[`ModalFooterActions`](#modalfooteractions)`) => ReactNode)` | 取消 + 确定 | 自定义底部；null 隐藏；函数接收默认按钮                                                                                                                                                      |
| `icon`               | `ReactNode`                                                                            | —       | 标题左侧的装饰图标。                                                                                                                                                                  |
| `divided`            | `boolean`                                                                              | `true`  | 用浅分隔线划分标题、内容和底部操作区。                                                                                                                                                         |
| `width`              | `number \| string`                                                                     | `480`   | 弹窗宽度，数字为像素                                                                                                                                                                  |
| `closable`           | `boolean`                                                                              | `true`  | 显示右上角关闭按钮。                                                                                                                                                                  |
| `maskClosable`       | `boolean`                                                                              | `true`  | 点击遮罩时请求关闭。                                                                                                                                                                  |
| `keyboard`           | `boolean`                                                                              | `true`  | 允许按 Escape 请求关闭。                                                                                                                                                            |
| `initialFocus`       | `RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)`                        | —       | 指定初始焦点；默认聚焦首个可聚焦元素，可能是关闭按钮。                                                                                                                                                 |
| `returnFocus`        | `boolean \| RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)`             | —       | 关闭后返回原焦点；也可指定目标或设为 false。                                                                                                                                                   |
| `afterClose`         | `() => void`                                                                           | —       | 关闭动画完成后触发                                                                                                                                                                   |
| `destroyOnClose`     | `boolean`                                                                              | `false` | 关闭后卸载内容；preserve 优先，forceRender 会保持挂载。                                                                                                                                      |
| `preserve`           | `boolean`                                                                              | —       | 指定是否保留内容，优先于 destroyOnClose；不重置组件外的受控状态。                                                                                                                                    |
| `forceRender`        | `boolean`                                                                              | `false` | 打开前也挂载内容，关闭时保持隐藏。                                                                                                                                                           |
| `container`          | `Element \| DocumentFragment \| (() => Element \| DocumentFragment)`                   | —       | 指定 Portal 挂载目标，也可返回 ShadowRoot。                                                                                                                                             |

### ModalTabs API

内嵌标签页的可用属性见 [Tabs API
](tabs.html#tabs-api)（新标签页打开）。Modal 固定使用 `type="line"`
 与 `placement="top"`
，标签栏固定在正文滚动区上方，底部分割线不受 `divided={false}`
 影响；`items`
 为空时恢复普通弹窗。
```ts
type ModalTabsProps = Omit<TabsProps, 'type' | 'placement' | 'children'>;
```

### ModalFooterActions

底部渲染函数收到的默认确认与取消按钮。

| 属性              | 类型          | 默认值 | 说明            |
| --------------- | ----------- | --- | ------------- |
| `confirmButton` | `ReactNode` | 必填  | 默认确认按钮，保留加载状态 |
| `cancelButton`  | `ReactNode` | 必填  | 默认取消按钮        |

### DialogFocusOptions

配置对话框打开和关闭时的焦点处理。

| 属性             | 类型                                                                         | 默认值 | 说明                        |
| -------------- | -------------------------------------------------------------------------- | --- | ------------------------- |
| `initialFocus` | `RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)`            | —   | 指定打开后的初始焦点。               |
| `returnFocus`  | `boolean \| RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)` | —   | 关闭后返回原焦点；也可指定目标或设为 false。 |
