useSelectedLayoutSegment
useSelectedLayoutSegment
是一個 客戶端元件 (Client Component) 鉤子,可讓您讀取從中呼叫的 Layout 下方一層 的當前路由區段。
這對於導航 UI 非常有用,例如父佈局中的標籤頁,可以根據當前活動的子區段改變樣式。
'use client'
import { useSelectedLayoutSegment } from 'next/navigation'
export default function ExampleClientComponent() {
const segment = useSelectedLayoutSegment()
return <p>當前活動區段: {segment}</p>
}
'use client'
import { useSelectedLayoutSegment } from 'next/navigation'
export default function ExampleClientComponent() {
const segment = useSelectedLayoutSegment()
return <p>當前活動區段: {segment}</p>
}
須知事項:
- 由於
useSelectedLayoutSegment
是一個 客戶端元件 (Client Component) 鉤子,而佈局 (Layouts) 預設是 伺服器元件 (Server Components),因此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
來建立一個會根據當前活動區段改變樣式的連結元件。例如,部落格側邊欄中的精選文章列表:
// 將客戶端元件導入到父佈局 (伺服器元件) 中
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>
)
}
// 將客戶端元件導入到父佈局 (伺服器元件) 中
import { BlogNavLink } from './blog-nav-link'
import getFeaturedPosts from './get-featured-posts'
export default async function Layout({ children }) {
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 。 |