useSelectedLayoutSegment

useSelectedLayoutSegment 是一个客户端组件 (Client Component) 钩子,用于读取调用它的布局下一层级的活动路由片段。

该钩子适用于导航 UI,例如父布局中的标签页可以根据活动子片段改变样式。

'use client'

import { useSelectedLayoutSegment } from 'next/navigation'

export default function ExampleClientComponent() {
  const segment = useSelectedLayoutSegment()

  return <p>Active segment: {segment}</p>
}

须知:

参数

const segment = useSelectedLayoutSegment(parallelRoutesKey?: string)

useSelectedLayoutSegment 可选 接受一个 parallelRoutesKey,用于读取该插槽内的活动路由片段。

返回值

useSelectedLayoutSegment 返回活动片段的字符串,如果不存在则返回 null

例如,给定以下布局和 URL,返回的片段如下:

布局访问的 URL返回的片段
app/layout.js/null
app/layout.js/dashboard'dashboard'
app/dashboard/layout.js/dashboardnull
app/dashboard/layout.js/dashboard/settings'settings'
app/dashboard/layout.js/dashboard/analytics'analytics'
app/dashboard/layout.js/dashboard/analytics/monthly'analytics'

示例

创建活动链接组件

您可以使用 useSelectedLayoutSegment 创建一个活动链接组件,根据活动片段改变样式。例如,博客侧边栏中的精选文章列表:

'use client'

import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'

// 此*客户端*组件将被导入到博客布局中
export default function BlogNavLink({
  slug,
  children,
}: {
  slug: string
  children: React.ReactNode
}) {
  // 导航到 `/blog/hello-world` 将返回 'hello-world'
  // 作为选中的布局片段
  const segment = useSelectedLayoutSegment()
  const isActive = slug === segment

  return (
    <Link
      href={`/blog/${slug}`}
      // 根据链接是否活动改变样式
      style={{ fontWeight: isActive ? 'bold' : 'normal' }}
    >
      {children}
    </Link>
  )
}

版本历史

版本变更
v13.0.0引入 useSelectedLayoutSegment

On this page