| import React, { useState, useEffect } from 'react'; |
| import './Header.css'; |
| import logo from '../assets/logo.png'; |
| import { useUser } from '../context/UserContext'; |
| |
| const Header = () => { |
| const [currentPath, setCurrentPath] = useState(window.location.pathname); |
| const { user } = useUser(); |
| |
| const navLinks = [ |
| { to: '/friend-moments', label: '好友动态' }, |
| { to: '/forum', label: '论坛' }, |
| { to: '/interest-groups', label: '兴趣小组' }, |
| { to: '/seed-list', label: '种子列表' }, |
| { to: '/publish-seed', label: '发布种子' }, |
| ]; |
| |
| useEffect(() => { |
| const handleLocationChange = () => { |
| setCurrentPath(window.location.pathname); |
| }; |
| window.addEventListener('popstate', handleLocationChange); |
| return () => { |
| window.removeEventListener('popstate', handleLocationChange); |
| }; |
| }, []); |
| |
| const isActive = (path) => currentPath.startsWith(path); |
| |
| const handleLinkClick = (to) => { |
| window.history.pushState({}, '', to); |
| setCurrentPath(to); |
| }; |
| |
| return ( |
| <div className="main-page"> |
| <header className="header"> |
| <div className="logo-and-name"> |
| <img src={logo} alt="网站 logo" className="logo" /> |
| <span className="site-name">Echo</span> |
| </div> |
| <div className="user-and-message"> |
| <a href="/user/profile"> |
| <img |
| src={user?.avatarUrl} |
| alt="用户头像" |
| className="user-avatar" |
| /> |
| </a> |
| <span |
| className="message-center" |
| onClick={() => handleLinkClick('/messages')} |
| style={{ cursor: 'pointer' }} |
| > |
| 消息 |
| </span> |
| </div> |
| </header> |
| |
| <nav className="nav"> |
| {navLinks.map(({ to, label }) => ( |
| <a |
| key={to} |
| href={to} |
| onClick={(e) => { |
| e.preventDefault(); |
| handleLinkClick(to); |
| }} |
| className={`nav-item ${isActive(to) ? 'active' : ''}`} |
| > |
| {label} |
| </a> |
| ))} |
| </nav> |
| </div> |
| ); |
| }; |
| |
| export default Header; |