34 lines
957 B
TypeScript
34 lines
957 B
TypeScript
import { useEffect, useState, useCallback } from 'react';
|
|
|
|
// 全局 Toast 系统
|
|
let pushToast: ((message: string, type?: string) => void) | null = null;
|
|
|
|
export function toast(message: string, type = 'success') {
|
|
if (pushToast) pushToast(message, type);
|
|
}
|
|
|
|
export default function ToastContainer() {
|
|
const [items, setItems] = useState<any[]>([]);
|
|
|
|
const add = useCallback((message: string, type?: string) => {
|
|
const id = Date.now() + Math.random();
|
|
setItems(prev => [...prev, { id, message, type }]);
|
|
setTimeout(() => {
|
|
setItems(prev => prev.filter((t: any) => t.id !== id));
|
|
}, 3000);
|
|
}, []);
|
|
|
|
useEffect(() => { pushToast = add; return () => { pushToast = null; }; }, [add]);
|
|
|
|
return (
|
|
<div className="toast-container">
|
|
{items.map(t => (
|
|
<div key={t.id} className={`toast toast-${t.type}`}>
|
|
<span className="toast-dot"></span>
|
|
{t.message}
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|