useSelectedLayoutSegment
useSelectedLayoutSegment
是一個客戶端元件 (Client Component) 鉤子,可讓你讀取從呼叫它的佈局 (Layout)往下一個層級的當前路由區段 (active route segment)。
這對於導航 UI 非常有用,例如父佈局內的標籤頁,可以根據當前子區段來改變樣式。
須知事項:
- 由於
useSelectedLayoutSegment
是一個客戶端元件 (Client Component) 鉤子,而佈局 (Layouts) 預設是伺服器元件 (Server Components),因此useSelectedLayoutSegment
通常透過導入到佈局中的客戶端元件來呼叫。useSelectedLayoutSegment
只會返回往下一個層級的區段。若要返回所有當前區段,請參閱useSelectedLayoutSegments
參數
useSelectedLayoutSegment
可選地 接受一個 parallelRoutesKey
,這讓你可以讀取該插槽 (slot) 內的當前路由區段。
返回值
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
來建立一個會根據當前區段改變樣式的當前連結元件。例如,部落格側邊欄的精選文章列表:
版本歷史
版本 | 變更 |
---|---|
v13.0.0 | 引入 useSelectedLayoutSegment 。 |