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

# Sonner

反馈`@rockshin/tao-ui`

[代码演示](#代码演示)[API](#api)

通过命令式 API 展示短暂 toast 通知、异步状态与操作反馈。

## 何时使用

操作结果不需要持续占据页面空间时使用 Sonner。

**推荐**

- 消息简短并说明结果。
- 异步操作使用 loading 或 promise 生命周期。
- 关键恢复操作可以提供 action。

**避免**

- 不要用 toast 承载必须阅读的长期信息。

## 代码演示

每组示例独立运行，通知只出现在当前预览内。复制到应用时通常只需挂载一个 `Sonner`。


### 基础用法
```tsx preview="iframe-follow"
import { Button, Sonner, toast } from '@rockshin/tao-ui';

function SonnerExample() {
  return (
    <>
      <Button
        onClick={() =>
          toast.success({
            title: 'Saved',
            description: 'Your profile has been updated.',
          })
        }
      >
        Show toast
      </Button>
      <Sonner />
    </>
  );
}

export default SonnerExample;
```

### 语义化彩色 Toast
```tsx preview="iframe-follow"
import { Button, Sonner, Stack, toast } from '@rockshin/tao-ui';

function SemanticToasts() {
  return (
    <>
      <Stack direction="horizontal" gap="sm">
        <Button
          variant="secondary"
          onClick={() =>
            toast.info({
              title: 'Info',
              description: 'A new version is ready.',
            })
          }
        >
          Info
        </Button>
        <Button
          variant="secondary"
          onClick={() => toast.success({ title: 'Saved' })}
        >
          Success
        </Button>
        <Button
          variant="secondary"
          onClick={() => toast.warning({ title: 'Almost full' })}
        >
          Warning
        </Button>
        <Button
          variant="secondary"
          onClick={() => toast.error({ title: 'Build failed' })}
        >
          Error
        </Button>
      </Stack>
      <Sonner richColors closeButton />
    </>
  );
}

export default SemanticToasts;
```

### 加载与 Promise 生命周期
```tsx preview="iframe-follow"
import { Button, Sonner, Stack, toast } from '@rockshin/tao-ui';

const wait = (duration: number) =>
  new Promise((resolve) => window.setTimeout(resolve, duration));

function AsyncToasts() {
  return (
    <>
      <Stack direction="horizontal" gap="sm">
        <Button
          onClick={() => {
            const id = toast.loading({ title: 'Syncing workspace' });
            window.setTimeout(() => {
              toast.dismiss(id);
              toast.success({ title: 'Workspace synced' });
            }, 1200);
          }}
        >
          Loading
        </Button>
        <Button
          variant="secondary"
          onClick={() =>
            toast.promise(wait(1200), {
              loading: { title: 'Publishing' },
              success: { title: 'Published' },
              error: { title: 'Publish failed' },
            })
          }
        >
          Promise
        </Button>
      </Stack>
      <Sonner richColors />
    </>
  );
}

export default AsyncToasts;
```

### 操作、位置与堆叠限制
```tsx preview="iframe-follow"
import { Button, Sonner, Stack, toast } from '@rockshin/tao-ui';

function ActionToasts() {
  return (
    <>
      <Stack direction="horizontal" gap="sm">
        <Button
          onClick={() =>
            toast({
              title: 'Message sent',
              action: {
                label: 'Undo',
                onClick: () => toast.success({ title: 'Send reverted' }),
              },
            })
          }
        >
          With action
        </Button>
        <Button
          variant="secondary"
          onClick={() => toast.info({ title: 'Top right' })}
        >
          Positioned
        </Button>
        <Button variant="ghost" onClick={() => toast.dismiss()}>
          Dismiss all
        </Button>
      </Stack>
      <Sonner position="top-right" visibleToasts={3} closeButton />
    </>
  );
}

export default ActionToasts;
```

### 语义颜色
richColors 为状态通知提供区分。
```tsx preview="iframe-follow"
import { Button, Sonner, Stack, toast } from '@rockshin/tao-ui';

export default function SonnerRichColors() {
  return (
    <>
      <Stack direction="horizontal" gap="sm">
        <Button
          onClick={() =>
            toast.info({
              title: 'Deploy started',
              description: 'We will notify you when it finishes.',
              action: { label: 'View' },
            })
          }
        >
          Info
        </Button>
        <Button
          variant="secondary"
          onClick={() =>
            toast.error({
              title: 'Build failed',
              description: 'Check logs and retry.',
              cancel: { label: 'Dismiss' },
            })
          }
        >
          Error
        </Button>
      </Stack>
      <Sonner richColors closeButton />
    </>
  );
}
```

### 通知操作
action 与 cancel 提供相关操作。
```tsx preview="iframe-follow"
import { Button, Sonner, Stack, toast } from '@rockshin/tao-ui';

export default function SonnerActions() {
  return (
    <>
      <Stack direction="horizontal" gap="sm">
        <Button
          onClick={() =>
            toast({
              title: 'Message sent',
              description: 'Your message has been delivered.',
              action: {
                label: 'Undo',
                onClick: () =>
                  toast.warning({
                    title: 'Send reverted',
                    description: 'Draft restored to composer.',
                  }),
              },
              cancel: { label: 'Dismiss' },
            })
          }
        >
          Undo toast
        </Button>
        <Button
          variant="secondary"
          onClick={() =>
            toast.warning({
              title: 'Storage almost full',
              description: 'Delete unused files or upgrade your plan.',
              action: { label: 'Manage storage' },
            })
          }
        >
          Warning action
        </Button>
      </Stack>
      <Sonner closeButton richColors />
    </>
  );
}
```

### 通知位置
选择通知的显示位置，通知保留在预览窗口内。
```tsx preview="iframe-follow"
import { Button, Sonner, Stack, toast } from '@rockshin/tao-ui';

export default function SonnerPositions() {
  return (
    <>
      <Stack
        direction="horizontal"
        gap="sm"
        styles={{ root: { flexWrap: 'wrap' } }}
      >
        <Button
          onClick={() =>
            toast({
              title: 'Top left',
              description: 'Positioned in the top-left corner.',
            })
          }
        >
          Trigger
        </Button>
      </Stack>
      <Sonner position="top-left" />
    </>
  );
}
```

### 堆叠与数量上限
visibleToasts 限制同时可见的通知数量。
```tsx preview="iframe-follow"
import { Button, Sonner, Stack, toast } from '@rockshin/tao-ui';

export default function SonnerStackAndLimit() {
  return (
    <>
      <Stack direction="horizontal" gap="sm">
        <Button
          onClick={() => {
            for (let index = 1; index <= 5; index += 1) {
              toast({
                title: `Queued task #${index}`,
                description: `Background job ${index} is now running.`,
              });
            }
          }}
        >
          Push 5 toasts
        </Button>
        <Button variant="ghost" onClick={() => toast.dismiss()}>
          Clear all
        </Button>
      </Stack>
      <Sonner visibleToasts={3} />
    </>
  );
}
```

### 显示时长
每条通知可以覆盖默认时长，常驻通知需要明确关闭入口。
```tsx preview="iframe-follow"
import { Button, Sonner, Stack, toast } from '@rockshin/tao-ui';

export default function SonnerCustomDuration() {
  return (
    <>
      <Stack direction="horizontal" gap="sm">
        <Button
          onClick={() =>
            toast({
              title: 'Autosaves enabled',
              description: 'This one disappears quickly.',
              duration: 1200,
            })
          }
        >
          Short
        </Button>
        <Button
          variant="secondary"
          onClick={() =>
            toast({
              title: 'Manual review needed',
              description: 'This one stays longer for attention.',
              duration: 8000,
            })
          }
        >
          Long
        </Button>
      </Stack>
      <Sonner closeButton />
    </>
  );
}
```

### 表单提交反馈
本地延迟模拟提交，展示等待、成功和失败反馈。
```tsx preview="iframe-follow"
import { Button, Sonner, Stack, toast } from '@rockshin/tao-ui';

function wait(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export default function SonnerFormSubmit() {
  return (
    <>
      <Stack direction="horizontal" gap="sm">
        <Button
          onClick={async () => {
            await toast.promise(wait(1200), {
              loading: {
                title: 'Submitting form',
                description: 'Validating fields and saving changes.',
              },
              success: {
                title: 'Profile updated',
                description: 'Name, email, and preferences are saved.',
              },
              error: {
                title: 'Submit failed',
              },
            });
          }}
        >
          Submit profile
        </Button>
        <Button
          variant="secondary"
          onClick={() =>
            toast
              .promise(
                wait(1200).then(() => {
                  throw new Error('Card declined');
                }),
                {
                  loading: {
                    title: 'Submitting payment',
                    description: 'Contacting payment gateway.',
                  },
                  success: { title: 'Paid' },
                  error: (error) => ({
                    title: 'Payment failed',
                    description: (error as Error).message,
                  }),
                },
              )
              .catch(() => undefined)
          }
        >
          Submit payment
        </Button>
      </Stack>
      <Sonner richColors />
    </>
  );
}
```

## API


### [#](#sonner)Sonner



| 属性 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| className | 节点类名 | `string | undefined` | `-` |
| style | 节点样式 | `CSSProperties | undefined` | `-` |



### [#](#toast)toast



| 属性 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |

