useSelectedLayoutSegment
useSelectedLayoutSegment
是一個客戶端組件 Hook,可讓您讀取從中呼叫它的佈局下一層的作用中路由區段。
它適用於導航 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
是一個客戶端組件 Hook,而佈局預設為伺服器組件,因此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 已推出。 |
這有幫助嗎?