blob: fb3a3e10583bc3ebd1c6c59f3a12eb9e5e6f0c32 [file] [log] [blame]
22301009007da0e2025-04-15 21:24:46 +08001import React, { useState, useEffect } from 'react';
223010095b28c672025-04-10 20:12:45 +08002import './Header.css'; // 导入 Header.css 文件
3import logo from '../assets/logo.png';
4
5const Header = () => {
22301009007da0e2025-04-15 21:24:46 +08006 const [currentPath, setCurrentPath] = useState(window.location.pathname);
223010095b28c672025-04-10 20:12:45 +08007
22301009007da0e2025-04-15 21:24:46 +08008 // 提取所有页面路径,简化 active 类逻辑
9 const navLinks = [
10 { to: '/friend-moments', label: '好友动态' },
11 { to: '/forum', label: '论坛' },
12 { to: '/interest-groups', label: '兴趣小组' },
13 { to: '/seed-list', label: '种子列表' },
14 { to: '/publish-seed', label: '发布种子' },
15 ];
16
17 // 更新当前路径状态
18 useEffect(() => {
19 const handleLocationChange = () => {
20 setCurrentPath(window.location.pathname);
21 };
22
23 // 监听历史记录变化
24 window.addEventListener('popstate', handleLocationChange);
25
26 // 清理事件监听器
27 return () => {
28 window.removeEventListener('popstate', handleLocationChange);
29 };
30 }, []);
31
32 // 判断路径是否是当前活动页面
33 const isActive = (path) => currentPath.startsWith(path);
34
35 // 自定义链接点击逻辑
36 const handleLinkClick = (to) => {
37 window.history.pushState({}, '', to);
38 setCurrentPath(to); // 更新当前路径状态
39 };
223010095b28c672025-04-10 20:12:45 +080040
41 return (
42 <div className="main-page">
43 {/* 顶部栏 */}
44 <header className="header">
45 {/* 左侧 logo 和网站名称 */}
46 <div className="logo-and-name">
47 <img src={logo} alt="网站 logo" className="logo" />
48 <span className="site-name">Echo</span>
49 </div>
50 {/* 右侧用户头像和消息中心 */}
51 <div className="user-and-message">
22301009007da0e2025-04-15 21:24:46 +080052 {/* 用户头像点击跳转到个人主页 */}
53 <a href="/user/profile">
54 <img src="user-avatar.png" alt="用户头像" className="user-avatar" />
55 </a>
223010095b28c672025-04-10 20:12:45 +080056 <span className="message-center">消息</span>
57 </div>
58 </header>
22301009007da0e2025-04-15 21:24:46 +080059
223010095b28c672025-04-10 20:12:45 +080060 {/* 导航栏 */}
61 <nav className="nav">
22301009007da0e2025-04-15 21:24:46 +080062 {navLinks.map(({ to, label }) => (
63 <a
64 key={to}
65 href={to}
66 onClick={(e) => {
67 e.preventDefault(); // 防止默认跳转行为
68 handleLinkClick(to); // 手动更新当前路径
69 }}
70 className={`nav-item ${isActive(to) ? 'active' : ''}`}
71 >
72 {label}
73 </a>
74 ))}
223010095b28c672025-04-10 20:12:45 +080075 </nav>
76 </div>
77 );
78};
79
80export default Header;