useSelectedLayoutSegment
useSelectedLayoutSegment
是一个**客户端组件**钩子,允许您读取其调用的布局**下一级**的活动路由段。
它对于导航 UI(例如,父布局内的选项卡,其样式根据活动子段更改)很有用。
app/example-client-component.tsx
'use client'
import { useSelectedLayoutSegment } from 'next/navigation'
export default function ExampleClientComponent() {
const segment = useSelectedLayoutSegment()
return <p>Active segment: {segment}</p>
}
值得注意:
- 由于
useSelectedLayoutSegment
是一个客户端组件钩子,并且布局默认情况下是服务器组件,因此useSelectedLayoutSegment
通常通过导入到布局中的客户端组件调用。useSelectedLayoutSegment
仅返回下一级的段。要返回所有活动段,请参阅useSelectedLayoutSegments
参数
const segment = useSelectedLayoutSegment(parallelRoutesKey?: string)
useSelectedLayoutSegment
可选地接受parallelRoutesKey
,它允许您读取该插槽中的活动路由段。
返回值
useSelectedLayoutSegment
返回活动段的字符串,如果不存在,则返回null
。
例如,给定以下布局和 URL,返回的段将是
布局 | 访问的 URL | 返回的段 |
---|---|---|
app/layout.js | / | null |
app/layout.js | /dashboard | 'dashboard' |
app/dashboard/layout.js | /dashboard | null |
app/dashboard/layout.js | /dashboard/settings | 'settings' |
app/dashboard/layout.js | /dashboard/analytics | 'analytics' |
app/dashboard/layout.js | /dashboard/analytics/monthly | 'analytics' |
示例
创建活动链接组件
您可以使用useSelectedLayoutSegment
创建一个活动链接组件,该组件根据活动段更改样式。例如,博客侧边栏中的特色文章列表
app/blog/blog-nav-link.tsx
'use client'
import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'
// This *client* component will be imported into a blog layout
export default function BlogNavLink({
slug,
children,
}: {
slug: string
children: React.ReactNode
}) {
// Navigating to `/blog/hello-world` will return 'hello-world'
// for the selected layout segment
const segment = useSelectedLayoutSegment()
const isActive = slug === segment
return (
<Link
href={`/blog/${slug}`}
// Change style depending on whether the link is active
style={{ fontWeight: isActive ? 'bold' : 'normal' }}
>
{children}
</Link>
)
}
app/blog/layout.tsx
// Import the Client Component into a parent Layout (Server Component)
import { BlogNavLink } from './blog-nav-link'
import getFeaturedPosts from './get-featured-posts'
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
const featuredPosts = await getFeaturedPosts()
return (
<div>
{featuredPosts.map((post) => (
<div key={post.id}>
<BlogNavLink slug={post.slug}>{post.title}</BlogNavLink>
</div>
))}
<div>{children}</div>
</div>
)
}
版本历史记录
版本 | 更改 |
---|---|
v13.0.0 | 引入useSelectedLayoutSegment 。 |