|
| 1 | +import { useEffect, useRef, useState } from "react"; |
| 2 | + |
| 3 | +const TopLoadingBar = () => { |
| 4 | + const [isVisible, setIsVisible] = useState(false); |
| 5 | + const [progress, setProgress] = useState(0); |
| 6 | + const intervalRef = useRef(null); |
| 7 | + |
| 8 | + useEffect(() => { |
| 9 | + // 监听全局事件 |
| 10 | + const handleShow = () => { |
| 11 | + setIsVisible(true); |
| 12 | + setProgress(0); |
| 13 | + |
| 14 | + // 清除可能存在的旧interval |
| 15 | + if (intervalRef.current) { |
| 16 | + clearInterval(intervalRef.current); |
| 17 | + } |
| 18 | + |
| 19 | + // 模拟进度 |
| 20 | + let currentProgress = 0; |
| 21 | + intervalRef.current = setInterval(() => { |
| 22 | + currentProgress += Math.random() * 10; |
| 23 | + if (currentProgress >= 90) { |
| 24 | + clearInterval(intervalRef.current); |
| 25 | + } |
| 26 | + setProgress(currentProgress); |
| 27 | + }, 200); |
| 28 | + }; |
| 29 | + |
| 30 | + const handleHide = () => { |
| 31 | + // 清除进度interval |
| 32 | + if (intervalRef.current) { |
| 33 | + clearInterval(intervalRef.current); |
| 34 | + intervalRef.current = null; |
| 35 | + } |
| 36 | + setProgress(100); |
| 37 | + setTimeout(() => { |
| 38 | + setIsVisible(false); |
| 39 | + setProgress(0); |
| 40 | + }, 300); |
| 41 | + }; |
| 42 | + |
| 43 | + // 添加全局事件监听器 |
| 44 | + window.addEventListener("loading:show", handleShow); |
| 45 | + window.addEventListener("loading:hide", handleHide); |
| 46 | + |
| 47 | + return () => { |
| 48 | + // 组件卸载时清理 |
| 49 | + if (intervalRef.current) { |
| 50 | + clearInterval(intervalRef.current); |
| 51 | + } |
| 52 | + window.removeEventListener("loading:show", handleShow); |
| 53 | + window.removeEventListener("loading:hide", handleHide); |
| 54 | + }; |
| 55 | + }, []); |
| 56 | + |
| 57 | + useEffect(() => { |
| 58 | + console.log(progress); |
| 59 | + }, [progress]); |
| 60 | + |
| 61 | + if (!isVisible) return null; |
| 62 | + |
| 63 | + return ( |
| 64 | + <div className="top-loading-bar"> |
| 65 | + <div |
| 66 | + className="loading-bar-progress" |
| 67 | + style={{ width: `${progress}%` }} |
| 68 | + ></div> |
| 69 | + </div> |
| 70 | + ); |
| 71 | +}; |
| 72 | + |
| 73 | +export default TopLoadingBar; |
0 commit comments