import React, { createContext, useState, useContext } from "react"; interface LoadingContextType { isLoading: boolean; showLoading: () => void; hideLoading: () => void; } const LoadingContext = createContext({ isLoading: false, showLoading: () => {}, hideLoading: () => {}, }); export const LoadingProvider: React.FC<{ children: React.ReactNode }> = ({ children, }) => { const [isLoading, setIsLoading] = useState(false); const showLoading = () => setIsLoading(true); const hideLoading = () => setIsLoading(false); return ( {children} {isLoading && (
加载中...
)} ); }; // 全局loading实例 let globalShowLoading: (() => void) | null = null; let globalHideLoading: (() => void) | null = null; export const LoadingContainer: React.FC = () => { const { showLoading, hideLoading } = useContext(LoadingContext); React.useEffect(() => { globalShowLoading = showLoading; globalHideLoading = hideLoading; return () => { globalShowLoading = null; globalHideLoading = null; }; }, [showLoading, hideLoading]); return null; }; // 导出loading方法 export const loading = { show: () => { if (!globalShowLoading) { console.warn("Loading system not initialized"); return; } globalShowLoading(); }, hide: () => { if (!globalHideLoading) { console.warn("Loading system not initialized"); return; } globalHideLoading(); }, };