apps/docs/content/docs/cn/react/migration/(components)/toast.mdx
在 v2 中,Toast 采用 Provider + Hook 模式:
import { ToastProvider, useToast } from "@heroui/react";
function App() {
return (
<ToastProvider>
<MyComponent />
</ToastProvider>
);
}
function MyComponent() {
const { toast } = useToast();
return (
<button onClick={() => toast.show("Hello!")}>
Show Toast
</button>
);
}
在 v3 中,Toast 改为 Provider 组件 + 全局 toast() 函数:
import { Toast } from "@heroui/react";
function App() {
return (
<>
<Toast.Provider />
<MyComponent />
</>
);
}
function MyComponent() {
return (
<button onClick={() => toast("Hello!")}>
Show Toast
</button>
);
}
v2: 必须使用 ToastProvider 包裹
v3: 改用 Toast.Provider 组件(可放置在任意位置)
v2: 使用 useToast() Hook
v3: 直接调用 toast() 函数
v2: 使用 toast.show() 方法
v3: toast() 是带有辅助方法的函数(toast.success()、toast.danger() 等)
v2: 变体如 success、error、warning、info
v3: 变体:default、accent、success、warning、danger
v3: Toast 通过复合组件支持自定义渲染:
Toast —— Toast 主容器Toast.Content —— 内容包装器Toast.Title —— 标题文字Toast.Description —— 描述文字Toast.Indicator —— 图标 / 指示器Toast.CloseButton —— 关闭按钮Toast.ActionButton —— 操作按钮v3: 内置 toast.promise() 方法,可处理异步操作
<Tabs items={["v2", "v3"]}> <Tab value="v2"> ```tsx const { toast } = useToast();
toast.show({
title: "Success",
description: "Your changes have been saved",
variant: "success"
});
```
toast.success("Success", {
description: "Your changes have been saved"
});
```
<Tabs items={["v2", "v3"]}> <Tab value="v2"> ```tsx const { toast } = useToast();
toast.show({ variant: "success", title: "Success" });
toast.show({ variant: "error", title: "Error" });
toast.show({ variant: "warning", title: "Warning" });
toast.show({ variant: "info", title: "Info" });
```
toast.success("Success");
toast.danger("Error");
toast.warning("Warning");
toast.info("Info");
```
<Tabs items={["v2", "v3"]}> <Tab value="v2"> ```tsx const { toast } = useToast();
const handleAsync = async () => {
try {
await someAsyncOperation();
toast.show({ title: "Success", variant: "success" });
} catch {
toast.show({ title: "Error", variant: "error" });
}
};
```
const handleAsync = async () => {
toast.promise(someAsyncOperation(), {
loading: "Processing...",
success: "Operation completed!",
error: "Operation failed"
});
};
```
<Tabs items={["v2", "v3"]}> <Tab value="v2"> ```tsx const { toast } = useToast();
toast.show({
title: "Custom",
render: (toast) => (
<div>Custom content</div>
)
});
```
<Toast.Provider>
{({ toast: toastItem }) => (
<Toast toast={toastItem}>
<ToastContent>
<ToastTitle>Custom content</ToastTitle>
</ToastContent>
</Toast>
)}
</Toast.Provider>
```
Toast.Provider 取代 ToastProvidertoast() 函数取代 useToast() Hookerror → danger、info → accent)toast.success()、toast.danger() 等toast.promise() 处理异步操作