import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

function ToastTriggerButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() =>
        toastManager.add({
          title: "Toast created",
          description: "This is a toast notification.",
        })
      }
    >
      Show toast
    </Button>
  );
}

export function ToastBasicDemo() {
  return (
    <Toasty>
      <ToastTriggerButton />
    </Toasty>
  );
}

安装

批量导入

import { Toasty, useKumoToastManager } from "@cloudflare/kumo";

细粒度导入

import { Toasty, useKumoToastManager } from "@cloudflare/kumo/components/toast";

用法

toast 系统由两部分组成:Toasty 提供者组件,以及用于触发 toast 的 useKumoToastManager() Hook。

import { Toasty, useKumoToastManager, Button } from "@cloudflare/kumo";

function ToastTrigger() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() =>
        toastManager.add({
          title: "Success!",
          description: "Your changes have been saved.",
        })
      }
    >
      Save changes
    </Button>
  );
}

export default function App() {
  return (
    <Toasty>
      <ToastTrigger />
      {/* Rest of your app */}
    </Toasty>
  );
}

设置

用 Toasty 提供者包裹你的应用 (或其中一部分)。这会建立 toast 上下文并渲染 toast 视口。

// In your app root or layout
import { Toasty } from "@cloudflare/kumo";

export function Layout({ children }) {
  return <Toasty>{children}</Toasty>;
}

示例

标题与说明

同时包含标题和说明的完整 toast。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

function ToastTriggerButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() =>
        toastManager.add({
          title: "Toast created",
          description: "This is a toast notification.",
        })
      }
    >
      Show toast
    </Button>
  );
}

export function ToastBasicDemo() {
  return (
    <Toasty>
      <ToastTriggerButton />
    </Toasty>
  );
}

仅标题

只有标题的简单 toast,适合简短消息。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

function ToastTitleOnlyButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() =>
        toastManager.add({
          title: "Settings saved",
        })
      }
    >
      Title only
    </Button>
  );
}

export function ToastTitleOnlyDemo() {
  return (
    <Toasty>
      <ToastTitleOnlyButton />
    </Toasty>
  );
}

仅说明

只有说明的 toast,适合更详细的消息。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

function ToastDescriptionOnlyButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() =>
        toastManager.add({
          description: "Your changes have been saved successfully.",
        })
      }
    >
      Description only
    </Button>
  );
}

export function ToastDescriptionOnlyDemo() {
  return (
    <Toasty>
      <ToastDescriptionOnlyButton />
    </Toasty>
  );
}

success 变体

确认和积极结果等场景使用 success 变体。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

/** Success toast with green accent border and check icon. */
function ToastSuccessButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      variant="primary"
      onClick={() =>
        toastManager.add({
          title: "Deployed successfully",
          description: "Your Worker is now live.",
          variant: "success",
        })
      }
    >
      Deploy Worker
    </Button>
  );
}

export function ToastSuccessDemo() {
  return (
    <Toasty>
      <ToastSuccessButton />
    </Toasty>
  );
}

多个 toast

多个 toast 会堆叠并平滑动画。悬停在堆叠上可将它们展开。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

function ToastMultipleButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() => {
        toastManager.add({
          title: "First toast",
          description: "This is the first notification.",
        });
        setTimeout(() => {
          toastManager.add({
            title: "Second toast",
            description: "This is the second notification.",
          });
        }, 500);
        setTimeout(() => {
          toastManager.add({
            title: "Third toast",
            description: "This is the third notification.",
          });
        }, 1000);
      }}
    >
      Show multiple toasts
    </Button>
  );
}

export function ToastMultipleDemo() {
  return (
    <Toasty>
      <ToastMultipleButton />
    </Toasty>
  );
}

函数式更新

基于 toast 的当前状态就地更新它。本示例在创建部署 toast 之后将其改为 success 状态。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

function ToastFunctionalUpdateButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() => {
        const id = toastManager.add({
          id: "functional-update",
          title: "Deploying Worker",
          description: "Uploading your changes.",
          variant: "info",
          data: { deployment: "in progress" },
        });

        setTimeout(() => {
          toastManager.update(id, (toast) => ({
            title: "Worker deployed",
            description: `Deployment was ${toast.data.deployment}.`,
            variant: "success",
          }));
        }, 1200);
      }}
    >
      Deploy Worker
    </Button>
  );
}

/** Demonstrates updating a toast from its current state. */
export function ToastFunctionalUpdateDemo() {
  return (
    <Toasty>
      <ToastFunctionalUpdateButton />
    </Toasty>
  );
}

error 变体

需要引起注意的关键问题使用 error 变体。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

function ToastErrorButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() =>
        toastManager.add({
          title: "Deployment failed",
          description: "Unable to connect to the server.",
          variant: "error",
        })
      }
    >
      Show error toast
    </Button>
  );
}

export function ToastErrorDemo() {
  return (
    <Toasty>
      <ToastErrorButton />
    </Toasty>
  );
}

warning 变体

警示性消息使用 warning 变体。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

function ToastWarningButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() =>
        toastManager.add({
          title: "Rate limit warning",
          description: "You're approaching your API quota.",
          variant: "warning",
        })
      }
    >
      Show warning toast
    </Button>
  );
}

export function ToastWarningDemo() {
  return (
    <Toasty>
      <ToastWarningButton />
    </Toasty>
  );
}

info 变体

中性的信息提示使用 info 变体。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

/** Info toast with blue accent border and info icon. */
function ToastInfoButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() =>
        toastManager.add({
          title: "New version available",
          description: "Kumo v4.2 includes performance improvements.",
          variant: "info",
        })
      }
    >
      Show info toast
    </Button>
  );
}

export function ToastInfoDemo() {
  return (
    <Toasty>
      <ToastInfoButton />
    </Toasty>
  );
}

自定义内容

使用 content 属性可渲染完全自定义的 toast 内容。

import { Button, Toasty, useKumoToastManager, Link } from "@cloudflare/kumo";
import { CheckCircleIcon } from "@phosphor-icons/react/dist/ssr";

function ToastCustomContentButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() =>
        toastManager.add({
          content: (
            <div>
              <div className="flex items-center gap-2">
                <CheckCircleIcon />
                <Link href="/">my-first-worker</Link> created!
              </div>
            </div>
          ),
        })
      }
    >
      Show custom content
    </Button>
  );
}

export function ToastCustomContentDemo() {
  return (
    <Toasty>
      <ToastCustomContentButton />
    </Toasty>
  );
}

操作按钮

为 toast 添加操作按钮,供用户交互。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

function ToastActionsButton() {
  const toastManager = useKumoToastManager();

  return (
    <Button
      onClick={() =>
        toastManager.add({
          title: "Need help?",
          description: "Get assistance with your deployment.",
          actions: [
            {
              children: "Support",
              variant: "secondary",
              onClick: () => console.log("Support clicked"),
            },
            {
              children: "Ask AI",
              variant: "primary",
              onClick: () => console.log("Ask AI clicked"),
            },
          ],
        })
      }
    >
      Show with actions
    </Button>
  );
}

export function ToastActionsDemo() {
  return (
    <Toasty>
      <ToastActionsButton />
    </Toasty>
  );
}

Promise

使用 promise 方法自动展示加载、成功和错误状态。

import { Button, Toasty, useKumoToastManager } from "@cloudflare/kumo";

function ToastPromiseButton() {
  const toastManager = useKumoToastManager();

  const simulateDeployment = () => {
    return new Promise<{ name: string }>((resolve, reject) => {
      setTimeout(() => {
        if (Math.random() > 0.3) {
          resolve({ name: "my-worker" });
        } else {
          reject(new Error("Network error"));
        }
      }, 2000);
    });
  };

  return (
    <Button
      onClick={() =>
        toastManager.promise(simulateDeployment(), {
          loading: {
            title: "Deploying...",
            description: "Please wait while we deploy your Worker.",
          },
          success: (data) => ({
            title: "Deployed!",
            description: `Worker "${data.name}" is now live.`,
          }),
          error: (err) => ({
            title: "Deployment failed",
            description: err.message,
            variant: "error",
          }),
        })
      }
    >
      Deploy with promise
    </Button>
  );
}

export function ToastPromiseDemo() {
  return (
    <Toasty>
      <ToastPromiseButton />
    </Toasty>
  );
}

API 参考

Toasty

包裹你的应用并管理 toast 系统的提供者组件。

属性类型默认值说明
variant"default" | "success" | "error" | "warning" | "info""default"-
children*React.ReactNode-Application content. Toasts render via a portal above this.
containerPortalContainer-Container element for the portal. Use this to render toasts inside a Shadow DOM or custom container. Overrides `KumoPortalProvider` context.
toastManagerReturnType<typeof createKumoToastManager>-Optional toast manager created by `createKumoToastManager()`. When provided, allows code outside the React tree (timers, module-load callbacks, query-cache listeners) to dispatch toasts via the same dedupe-aware manager that `useKumoToastManager()` returns inside the tree. Forwarded to the underlying `@base-ui/react/toast` `Toast.Provider` `toastManager` prop — see https://base-ui.com/react/components/toast for the upstream primitive.

useKumoToastManager()

一个返回 toast 管理器的 Hook,用于创建 toast。

const toastManager = useKumoToastManager();

// Add a toast
toastManager.add(options);

// Update from the current toast state
toastManager.update(toastId, (toast) => ({
  description: `Updated after ${toast.timeout ?? 5000}ms`,
}));

// Promise-based toast
toastManager.promise(asyncFn(), {
  loading: options,
  success: (data) => options,
  error: (err) => options,
});

Toast 选项

传给 toastManager.add() 和 promise 处理函数的选项。

属性类型默认值说明
titlestring—突出显示的 toast 标题。
descriptionstring—显示在标题下方的次要文本。
variant

“default” | “success” | “error” | “warning” | “info"

"default”toast 的视觉样式。
contentReactNode—

在 toast 内渲染的自定义内容,会覆盖 title 和 description。

actionsButtonProps[]—作为操作按钮渲染的按钮属性数组。
timeoutnumber5000

toast 自动消失前的毫秒数。