> Leaf UI 0.17.3 · Package: @ifhover/leaf-ui · Source: c3221834f84f2f48481a2054026b713456f8e5dc
> Browser documentation: https://ifhover.github.io/leaf-ui/components/confirm.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.

# Confirm 确认框

在执行重要操作前征求确认，并等待用户的选择。

编辑内容使用 [Modal](https://ifhover.github.io/leaf-ui/components/modal.md)，希望在触发按钮旁简短确认时使用 [Popconfirm](https://ifhover.github.io/leaf-ui/components/popconfirm.md)。

在应用入口接入 [ConfigProvider](https://ifhover.github.io/leaf-ui/components/config-provider.md)，子组件即可调用 `useConfirm()`。确认框沿用调用区域的主题和语言。

```tsx
import { ConfigProvider } from '@ifhover/leaf-ui';

export function Root() {
  return (
    <ConfigProvider>
      <App />
    </ConfigProvider>
  );
}
```


## 基础用法

[](#)
`confirm()` 返回 `Promise<boolean>`：确认得到 `true`，取消得到 `false`。


保存更改

simple.tsx

复制代码

```tsx lineNumbers file="../../src/examples/confirm/simple.tsx"
import { Button, Space, Text, useConfirm } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ConfirmSimple() {
  const { confirm } = useConfirm();
  const [result, setResult] = useState('');
  return (
    <Space direction="vertical" align="start">
      <Button
        onClick={async () => {
          const accepted = await confirm({
            title: '保存更改？',
            children: '保存后，新设置会立即生效。',
            confirmText: '保存',
            cancelText: '继续编辑',
          });
          setResult(accepted ? '更改已保存' : '已取消保存');
        }}
      >
        保存更改
      </Button>
      {result && (
        <Text tone="muted" role="status">
          {result}
        </Text>
      )}
    </Space>
  );
}
```

展开代码


## 示例

### 状态提示

通过 `type` 选择提示意图，默认为 `info`。`type="default"` 不显示内置图标，也可用 `icon={null}` 隐藏任意类型的图标。`success` 默认不显示取消按钮，需要时设置 `showCancel`。


信息提示成功提示警告确认

status.tsx

复制代码

```tsx lineNumbers file="../../src/examples/confirm/status.tsx"
import { Button, Space, useConfirm } from '@ifhover/leaf-ui';

export function ConfirmStatus() {
  const { confirm } = useConfirm();
  return (
    <Space wrap>
      <Button
        onClick={() =>
          confirm({ type: 'info', title: '分享链接？', children: '获得链接的人可以查看此页面。' })
        }
      >
        信息提示
      </Button>
      <Button
        onClick={() =>
          confirm({ type: 'success', title: '导出已准备就绪', children: '文件已生成，可以下载。' })
        }
      >
        成功提示
      </Button>
      <Button
        onClick={() =>
          confirm({
            type: 'warning',
            title: '离开当前页面？',
            children: '尚未保存的更改将会丢失。',
          })
        }
      >
        警告确认
      </Button>
    </Space>
  );
}
```

展开代码

### 异步确认

[](#)
将异步操作放入 `onConfirm`，成功后确认框自动关闭并返回 `true`。等待期间默认按钮显示加载状态，不能重复确认或取消。


删除项目

basic.tsx

复制代码

```tsx lineNumbers file="../../src/examples/confirm/basic.tsx"
import { Button, Space, Text, useConfirm } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ConfirmBasic() {
  const { confirm } = useConfirm();
  const [result, setResult] = useState('');
  return (
    <Space direction="vertical" align="start">
      <Button
        danger
        variant="outline"
        onClick={async () => {
          setResult('');
          const accepted = await confirm({
            title: '删除项目',
            children: '删除后无法恢复，请确认是否继续。',
            type: 'danger',
            onConfirm: () => new Promise<void>((resolve) => setTimeout(resolve, 900)),
          });
          setResult(accepted ? '项目已删除' : '已取消删除');
        }}
      >
        删除项目
      </Button>
      {result && (
        <Text tone="muted" role="status">
          {result}
        </Text>
      )}
    </Space>
  );
}
```

展开代码

### 失败与重试

`onConfirm` 抛出错误时显示错误并保持打开，可再次确认重试。此例每次打开都先失败一次，第二次成功。


提交与重试

retry.tsx

复制代码

```tsx lineNumbers file="../../src/examples/confirm/retry.tsx"
import { Button, Space, Text, useConfirm } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function ConfirmRetry() {
  const { confirm } = useConfirm();
  const [result, setResult] = useState('');
  return (
    <Space direction="vertical" align="start">
      <Button
        onClick={async () => {
          let attempts = 0;
          setResult('');
          const accepted = await confirm({
            type: 'warning',
            title: '提交更改？',
            children: '首次提交模拟失败，再次确认即可重试。',
            onConfirm: async () => {
              await new Promise<void>((resolve) => setTimeout(resolve, 600));
              if (++attempts === 1) throw new Error('暂时无法提交，请重试。');
            },
          });
          setResult(accepted ? '更改已提交' : '已取消提交');
        }}
      >
        提交与重试
      </Button>
      {result && (
        <Text tone="muted" role="status">
          {result}
        </Text>
      )}
    </Space>
  );
}
```

展开代码


## API

### useConfirm API

返回的对象类型是 [`ConfirmApi`](#confirmapi)。同一队列的请求依次展示，上一个完成关闭过渡后才显示下一个；Promise 在作出决定并开始关闭时返回结果，不等待关闭动画。

调用组件或 Provider 卸载时，未结束的请求返回 `false`；这不会中止已经执行的异步操作，也不会触发 `onCancel`。

| 属性        | 类型                                                                 | 默认值 | 说明                           |
| --------- | ------------------------------------------------------------------ | --- | ---------------------------- |
| `confirm` | [`(options: ConfirmOptions) => Promise<boolean>`](#confirmoptions) | —   | 确认返回 true；取消或调用区域卸载返回 false。 |

### ConfirmApi

`useConfirm()` 返回的命令接口。

| 属性        | 类型                                                                     | 默认值 | 说明                                                   |
| --------- | ---------------------------------------------------------------------- | --- | ---------------------------------------------------- |
| `confirm` | `(options: `[`ConfirmOptions`](#confirmoptions)`) => Promise<boolean>` | 必填  | 等待决定并返回 boolean；确认成功为 true，取消或调用区域卸载为 false，不等待关闭动画。 |

### ConfirmOptions

调用 `confirm()` 时提供的内容、操作和交互配置。

| 属性                   | 类型                                                                                 | 默认值                     | 说明                                |
| -------------------- | ---------------------------------------------------------------------------------- | ----------------------- | --------------------------------- |
| `title`              | `ReactNode`                                                                        | —                       | 确认标题。                             |
| `children`           | `ReactNode`                                                                        | —                       | 简短说明本次操作的影响。                      |
| `onConfirm`          | `() => void \| Promise<void>`                                                      | —                       | 确认操作；等待 Promise 成功后关闭，失败时保留并显示错误。 |
| `onCancel`           | `() => void`                                                                       | —                       | 取消时调用。                            |
| `type`               | `'default' \| 'danger' \| 'success' \| 'warning' \| 'info'`                        | `'info'`                | 状态图标与颜色；仅 danger 改变确定按钮颜色。        |
| `icon`               | `ReactNode`                                                                        | —                       | 标题旁的状态图标；无标题时位于正文旁，传入 null 隐藏。    |
| `confirmText`        | `ReactNode`                                                                        | 语言默认值                   | 确认按钮文字。                           |
| `cancelText`         | `ReactNode`                                                                        | 语言默认值                   | 取消按钮文字。                           |
| `showCancel`         | `boolean`                                                                          | success 为 false，其余 true | 是否展示取消按钮。                         |
| `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) | —                       | 取消按钮属性。                           |
| `width`              | `number \| string`                                                                 | `420`                   | 确认框宽度，数字为像素。                      |
| `closable`           | `boolean`                                                                          | `false`                 | 是否显示右上角关闭按钮。                      |
| `maskClosable`       | `boolean`                                                                          | `false`                 | 点击遮罩时取消。                          |
| `keyboard`           | `boolean`                                                                          | `true`                  | 按 Escape 时取消。                     |
| `initialFocus`       | `RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)`                    | —                       | 指定打开后的初始焦点。                       |
| `returnFocus`        | `boolean \| RefObject<HTMLElement \| null> \| (() => HTMLElement \| null)`         | —                       | 关闭后返回原焦点，也可指定目标或设为 false。         |
| `className`          | `string`                                                                           | —                       | 确认框类名。                            |
| `style`              | `CSSProperties`                                                                    | —                       | 确认框样式。                            |

### ConfirmProvider API

未使用 `ConfigProvider` 时，在入口放置 `ConfirmProvider`。显式添加 `ConfirmProvider` 会建立独立队列，嵌套 `ConfigProvider` 则继续共享已有队列。

```tsx
import { ConfirmProvider } from '@ifhover/leaf-ui';

export function Root() {
  return (
    <ConfirmProvider>
      <App />
    </ConfirmProvider>
  );
}
```

| 属性         | 类型          | 默认值 | 说明                                                           |
| ---------- | ----------- | --- | ------------------------------------------------------------ |
| `children` | `ReactNode` | —   | 共用此独立确认队列的内容；ConfigProvider 已自动提供队列，嵌套 ConfigProvider 不另建队列。 |
