Creation:2026-06-22Last update:2026-06-22
将此文档参考到您的 AI 助手ChatGPTClaudeDeepSeekGoogle AI modeGeminiPerplexityMistralGrok
使用您最喜欢的AI助手总结文档,并引用此页面和AI提供商
版本历史
- "添加 usePathname 实用工具"v10.0.02026/6/23
- "初始化历史"v8.2.02026/6/22
此页面的内容已使用 AI 翻译。
查看英文原文的最新版本Edit this doc
If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy
Copy doc Markdown to clipboard
Preact 集成: usePathname Hook 文档
usePathname 钩子返回移除了 locale(语言环境)片段的当前浏览器路径名 (pathname)。这在构建多语言感知的导航时非常有用(例如,确定哪个导航项处于活动状态),而无需手动去除 locale 前缀。
在 Preact 中引入 usePathname
typescript
复制代码
复制代码到剪贴板
import { usePathname } from "preact-intlayer";概览
usePathname 会读取 window.location.pathname,通过 getPathWithoutLocale 移除 locale 前缀,并在浏览器触发 popstate 事件(后退/前进导航)时重新渲染组件。在服务器端渲染(SSR)期间,它将返回一个空字符串。
用法
src/components/NavItem.tsx
复制代码
复制代码到剪贴板
import type { FunctionComponent } from "preact";import { usePathname } from "preact-intlayer";type NavItemProps = { href: string; label: string;};const NavItem: FunctionComponent<NavItemProps> = ({ href, label }) => { const pathname = usePathname(); const isActive = pathname === href; return ( <a href={href} aria-current={isActive ? "page" : undefined}> {label} </a> );};export default NavItem;返回值
显示表格的所有内容
在弹窗中打开表格以清晰地查看所有数据
| 类型 | 描述 |
|---|---|
string | 不包含 locale 前缀的当前路径名。在服务器端渲染(SSR)期间为空字符串。 |
行为表现
- 去除 Locale (Locale stripping): 移除 URL 开头的 locale 片段(例如
/zh/dashboard→/dashboard)。 - 响应式更新: 在
popstate事件(浏览器的后退/前进导航)发生时自动更新。 - SSR 安全: 当
window不可用时返回""。 - 清理 (Cleanup): 组件卸载时会自动移除
popstate监听器。
示例
src/components/Sidebar.tsx
复制代码
复制代码到剪贴板
import type { FunctionComponent } from "preact";import { usePathname } from "preact-intlayer";const links = [ { href: "/dashboard", label: "仪表盘" }, { href: "/settings", label: "设置" },];const Sidebar: FunctionComponent = () => { const pathname = usePathname(); return ( <nav> {links.map(({ href, label }) => ( <a key={href} href={href} style={{ fontWeight: pathname === href ? "bold" : "normal" }} > {label} </a> ))} </nav> );};export default Sidebar;相关信息
useLocale— 当前的 locale + 切换器getPathWithoutLocale— 该钩子使用的底层实用工具