Toast 组件使用指南
概述
自定义的全局 Toast 组件,支持命令式调用,无需在组件树中添加 Provider。
特性
- 🚀 轻量级,零依赖
- 📱 响应式设计
- 🎨 支持多种类型(success, error, warning, info)
- ⚡ 命令式 API,简单易用
- 🔧 高度可定制
- 🌙 支持暗色主题
快速开始
1. 基本用法
import toast from "@/components/Toast";
// 成功提示
toast.success("操作成功!");
// 错误提示
toast.error("操作失败!");
// 警告提示
toast.warning("请注意!");
// 信息提示
toast.info("这是一条信息");
2. 高级用法
// 自定义持续时间
toast.success("3秒后消失", { duration: 3000 });
// 永不自动消失
toast.info("手动关闭", { duration: 0 });
// 禁用关闭按钮
toast.error("无法关闭", { closable: false });
// 带标题的提示
toast.success("操作完成", {
title: "成功",
duration: 5000,
});
// 获取 Toast ID,手动关闭
const toastId = toast.info("loading...");
setTimeout(() => {
toast.remove(toastId);
}, 2000);
3. 在组件中使用 Hook(可选)
如果需要在组件内部管理 Toast 状态,可以使用 Provider 方式:
import { ToastProvider, useToast } from "@/components/Toast";
function App() {
return (
<ToastProvider>
<YourComponent />
</ToastProvider>
);
}
function YourComponent() {
const { addToast, removeAllToasts } = useToast();
const handleClick = () => {
addToast({
type: "success",
message: "这是通过 Hook 创建的 Toast",
});
};
return (
<div>
<button onClick={handleClick}>显示 Toast</button>
<button onClick={removeAllToasts}>清空所有 Toast</button>
</div>
);
}
API 参考
全局方法
toast.success(message, options?)- 显示成功提示toast.error(message, options?)- 显示错误提示toast.warning(message, options?)- 显示警告提示toast.info(message, options?)- 显示信息提示toast.remove(id)- 移除指定 Toasttoast.removeAll()- 移除所有 Toast
Options 参数
interface ToastOptions {
title?: string; // 标题
duration?: number; // 持续时间(毫秒),0 表示不自动关闭
closable?: boolean; // 是否显示关闭按钮,默认 true
type?: "success" | "error" | "warning" | "info"; // Toast 类型
}
Hook API
useToast()- 返回 Toast 管理方法addToast(options)- 添加 ToastremoveToast(id)- 移除指定 ToastremoveAllToasts()- 移除所有 Toasttoasts- 当前 Toast 列表
样式定制
可以通过修改 CSS 变量来定制样式:
.toast-item {
/* 自定义背景色 */
background: your-color;
/* 自定义圆角 */
border-radius: your-radius;
/* 自定义阴影 */
box-shadow: your-shadow;
}
注意事项
- Toast 容器会自动创建和销毁,无需手动管理
- 支持同时显示多个 Toast
- 在移动端会自动适配屏幕宽度
- 支持暗色主题自动切换