import React, { createContext, useContext, useState, useCallback } from 'react'; import { NotificationData } from '../types'; import Notification from '../components/UI/Notification'; interface NotificationContextType { notifications: NotificationData[]; showNotification: (title: string, message: string, type?: 'success' | 'error' | 'warning' | 'info', duration?: number) => void; removeNotification: (id: string) => void; clearAll: () => void; } const NotificationContext = createContext(undefined); export function NotificationProvider({ children }: { children: React.ReactNode }) { const [notifications, setNotifications] = useState([]); const showNotification = useCallback(( title: string, message: string, type: 'success' | 'error' | 'warning' | 'info' = 'info', duration: number = 5000 ) => { const id = `notification_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; const notification: NotificationData = { id, title, message, type, duration, timestamp: new Date().toISOString(), }; setNotifications(prev => [...prev, notification]); // 自动移除通知 if (duration > 0) { setTimeout(() => { removeNotification(id); }, duration); } }, []); const removeNotification = useCallback((id: string) => { setNotifications(prev => prev.filter(notification => notification.id !== id)); }, []); const clearAll = useCallback(() => { setNotifications([]); }, []); const value = { notifications, showNotification, removeNotification, clearAll, }; return ( {children} {/* 渲染通知组件 */}
{notifications.map(notification => ( removeNotification(notification.id)} /> ))}
); } export function useNotification() { const context = useContext(NotificationContext); if (context === undefined) { throw new Error('useNotification must be used within a NotificationProvider'); } return context; }