import React, { createContext, useState, useContext, useEffect } from "react"; interface Message { id: number; type: "success" | "error" | "info" | "warning"; content: string; duration?: number; } interface MessageOptions { content: string; duration?: number; } interface MessageContextType { messages: Message[]; addMessage: ( type: Message["type"], content: string, duration?: number, ) => void; } const MessageContext = createContext({ messages: [], addMessage: () => {}, }); export const MessageProvider: React.FC<{ children: React.ReactNode }> = ({ children, }) => { const [messages, setMessages] = useState([]); const removeMessage = (id: number) => { setMessages((prev) => prev.filter((msg) => msg.id !== id)); }; const addMessage = ( type: Message["type"], content: string, duration = 3000, ) => { const id = Date.now(); setMessages((prevMessages) => { const newMessages = [...prevMessages, { id, type, content }]; return newMessages; }); if (duration > 0) { setTimeout(() => removeMessage(id), duration); } }; return ( <> {children}
{messages.map((msg) => (
{msg.content}
))}
); }; // 修改全局消息实例的实现 let globalAddMessage: | ((type: Message["type"], content: string, duration?: number) => void) | null = null; export const MessageContainer: React.FC = () => { const { addMessage } = useContext(MessageContext); useEffect(() => { globalAddMessage = addMessage; return () => { globalAddMessage = null; }; }, [addMessage]); return null; }; // 修改消息方法的实现 export const message = { success: (content: string) => { if (!globalAddMessage) { console.warn("Message system not initialized"); return; } globalAddMessage("success", content); }, error: (content: string) => { if (!globalAddMessage) { console.warn("Message system not initialized"); return; } globalAddMessage("error", content); }, warning: (content: string) => { if (!globalAddMessage) { console.warn("Message system not initialized"); return; } globalAddMessage("warning", content); }, info: (content: string) => { if (!globalAddMessage) { console.warn("Message system not initialized"); return; } globalAddMessage("info", content); }, };