You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Preact-router Link切换页面时activeClassName不生效问题排查

解决preact-router Link组件跳转与激活样式共存问题

问题根源

你这问题出在两个地方:

  1. 从preact-router导入的Link得在Router上下文里才能检测当前路由,进而应用activeClassName,但你代码里的Link放在Router组件外面,拿不到路由状态,所以样式死活不生效。
  2. 从preact-router/match导入的Link只负责路径匹配,不带路由跳转功能,自然切不了页面。

你自己写的临时方案手动处理激活状态,但没监听路由变化(比如浏览器回退),所以回退时样式不会自动更新,而且逻辑也绕。

正确解决方案

方案一:把Link挪到Router里面

把带Link的nav移到Router组件内部,这样Link就能拿到路由上下文,自动给当前激活的链接加样式:

<main>
    <Router>
        <nav>
            {/* 根路径加exact,避免匹配所有子路径 */}
            <Link href="/" activeClassName="active-link" exact>Home</Link>
            <Link href="/someOtherPage" activeClassName="active-link">SomeOtherPage</Link>
        </nav>
        <Route path="/" component={Home} exact />
        <Route path="/someOtherPage" component={SomeOtherPage} />
    </Router>
</main>

方案二:用useLocation钩子手动控样式(适合Link必须在Router外的场景)

如果Link必须放在Router外面,就用preact-router自带的useLocation钩子监听当前路径,手动设置激活类:

import { Router, Route, Link, useLocation } from "preact-router";
import { QueryClient, QueryClientProvider } from "react-query";

import "./styles/app.css";

const queryClient = new QueryClient();

const App = () => {
    // 实时获取当前路由路径
    const location = useLocation();

    return (
        <QueryClientProvider client={queryClient}>
            <main>
                <nav>
                    <Link 
                        href="/" 
                        className={location.pathname === "/" ? "active-link" : ""}
                        exact
                    >
                        Home
                    </Link>
                    <Link 
                        href="/someOtherPage" 
                        className={location.pathname === "/someOtherPage" ? "active-link" : ""}
                    >
                        SomeOtherPage
                    </Link>
                </nav>
                <Router>
                    <Route path="/" component={Home} exact />
                    <Route path="/someOtherPage" component={SomeOtherPage} />
                </Router>
            </main>
        </QueryClientProvider>
    );
}

useLocation会自动监听路由变化,包括浏览器回退、前进,激活状态会实时更新,不用再手动写点击事件处理类名。

你的临时方案为啥不好

你用getCurrentUrl()只在组件第一次渲染时拿了一次路径,之后路由变了(比如回退)不会自动更新;而且手动循环清空类名再设置的逻辑,不仅麻烦,还容易覆盖其他可能的类名,不够稳妥。

内容的提问来源于stack exchange,提问作者Iisak_789

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 12:27:41