<Link> 是一个 React 组件,它扩展了 HTML <a> 元素,用于提供 预加载 和客户端路由之间的导航。它是 Next.js 中在路由之间导航的主要方式。
基本用法:
import Link from 'next/link'
export default function Page() {
return <Link href="/dashboard">Dashboard</Link>
}import Link from 'next/link'
export default function Page() {
return <Link href="/dashboard">Dashboard</Link>
}import Link from 'next/link'
export default function Home() {
return <Link href="/dashboard">Dashboard</Link>
}import Link from 'next/link'
export default function Home() {
return <Link href="/dashboard">Dashboard</Link>
}以下 props 可以传递给 <Link> 组件:
| Prop | 示例 | 类型 | 必填 |
|---|---|---|---|
href | href="/dashboard" | 字符串或对象 | 是 |
as | as="/post/abc" | 字符串或对象 | - |
replace | replace={false} | 布尔值 | - |
scroll | scroll={false} | 布尔值 | - |
prefetch | prefetch={false} | 布尔值 | - |
shallow | shallow={false} | 布尔值 | - |
locale | locale="fr" | 字符串或布尔值 | - |
onNavigate | onNavigate={(e) => {}} | 函数 | - |
| Prop | 示例 | 类型 | 必填 |
|---|---|---|---|
href | href="/dashboard" | 字符串或对象 | 是 |
replace | replace={false} | 布尔值 | - |
scroll | scroll={false} | 布尔值 | - |
prefetch | prefetch={false} | 布尔值或 null | - |
onNavigate | onNavigate={(e) => {}} | 函数 | - |
须知:
<a>标签属性,例如className或target="_blank",可以作为 props 添加到<Link>组件,并将传递给底层的<a>元素。
href (必填)要导航到的路径或 URL。
import Link from 'next/link'
// Navigate to /about?name=test
export default function Page() {
return (
<Link
href={{
pathname: '/about',
query: { name: 'test' },
}}
>
About
</Link>
)
}import Link from 'next/link'
// Navigate to /about?name=test
export default function Page() {
return (
<Link
href={{
pathname: '/about',
query: { name: 'test' },
}}
>
About
</Link>
)
}import Link from 'next/link'
// Navigate to /about?name=test
export default function Home() {
return (
<Link
href={{
pathname: '/about',
query: { name: 'test' },
}}
>
About
</Link>
)
}import Link from 'next/link'
// Navigate to /about?name=test
export default function Home() {
return (
<Link
href={{
pathname: '/about',
query: { name: 'test' },
}}
>
About
</Link>
)
}replace默认为 false。 当为 true 时,next/link 将替换当前历史状态,而不是在 浏览器历史记录 堆栈中添加新的 URL。
import Link from 'next/link'
export default function Page() {
return (
<Link href="/dashboard" replace>
Dashboard
</Link>
)
}import Link from 'next/link'
export default function Page() {
return (
<Link href="/dashboard" replace>
Dashboard
</Link>
)
}import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" replace>
Dashboard
</Link>
)
}import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" replace>
Dashboard
</Link>
)
}scroll默认为 true。 Next.js 中 <Link> 的默认滚动行为是保持滚动位置,类似于浏览器处理前进和后退导航的方式。当您导航到一个新的 Page 时,只要该 Page 在视口中可见,滚动位置就会保持不变。然而,如果该 Page 在视口中不可见,Next.js 将滚动到第一个 Page 元素的顶部。
当 scroll = {false} 时,Next.js 不会尝试滚动到第一个 Page 元素。
须知:Next.js 在管理滚动行为之前会检查
scroll: false。如果启用了滚动,它会识别导航相关的 DOM 节点并检查每个顶级元素。所有不可滚动和没有渲染 HTML 的元素都会被跳过,这包括粘性或固定定位的元素,以及不可见的元素(例如通过getBoundingClientRect计算的元素)。Next.js 然后继续遍历同级元素,直到找到一个在视口中可见的可滚动元素。
import Link from 'next/link'
export default function Page() {
return (
<Link href="/dashboard" scroll={false}>
Dashboard
</Link>
)
}import Link from 'next/link'
export default function Page() {
return (
<Link href="/dashboard" scroll={false}>
Dashboard
</Link>
)
}import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" scroll={false}>
Dashboard
</Link>
)
}import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" scroll={false}>
Dashboard
</Link>
)
}prefetch预加载发生在 <Link /> 组件进入用户视口时(初始时或通过滚动)。Next.js 在后台预取并加载链接的路由(由 href 指示)及其数据,以提高客户端导航的性能。如果预取的数据在用户悬停在 <Link /> 上时已过期,Next.js 将尝试再次预取。预加载仅在生产环境中启用。
以下值可以传递给 prefetch prop:
"auto" 或 null (默认):预加载行为取决于路由是静态还是动态。对于静态路由,将预加载完整路由(包括其所有数据)。对于动态路由,将预加载部分路由,直到最近的带有 loading.js 边界的段。true:将预加载静态和动态路由的完整路由。false:进入视口或悬停时都不会发生预加载。import Link from 'next/link'
export default function Page() {
return (
<Link href="/dashboard" prefetch={false}>
Dashboard
</Link>
)
}import Link from 'next/link'
export default function Page() {
return (
<Link href="/dashboard" prefetch={false}>
Dashboard
</Link>
)
}预加载发生在 <Link /> 组件进入用户视口时(初始时或通过滚动)。Next.js 在后台预取并加载链接的路由(由 href 指示)及其数据,以提高客户端导航的性能。预加载仅在生产环境中启用。
以下值可以传递给 prefetch prop:
true (默认):将预加载完整路由及其数据。false:进入视口时不会发生预加载,但在悬停时会发生。如果您也希望完全移除悬停时的预加载,请考虑使用 <a> 标签或 增量采用 App Router,这也可以禁用悬停时的预加载。import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" prefetch={false}>
Dashboard
</Link>
)
}import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" prefetch={false}>
Dashboard
</Link>
)
}shallow更新当前页面的路径,而无需重新运行 getStaticProps、getServerSideProps 或 getInitialProps。默认为 false。
import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" shallow={false}>
Dashboard
</Link>
)
}import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" shallow={false}>
Dashboard
</Link>
)
}locale活动的 locale 会自动前置。locale 允许提供不同的 locale。当 false 时,href 必须包含 locale,因为默认行为已被禁用。
import Link from 'next/link'
export default function Home() {
return (
<>
{/* Default behavior: locale is prepended */}
<Link href="/dashboard">Dashboard (with locale)</Link>
{/* Disable locale prepending */}
<Link href="/dashboard" locale={false}>
Dashboard (without locale)
</Link>
{/* Specify a different locale */}
<Link href="/dashboard" locale="fr">
Dashboard (French)
</Link>
</>
)
}import Link from 'next/link'
export default function Home() {
return (
<>
{/* Default behavior: locale is prepended */}
<Link href="/dashboard">Dashboard (with locale)</Link>
{/* Disable locale prepending */}
<Link href="/dashboard" locale={false}>
Dashboard (without locale)
</Link>
{/* Specify a different locale */}
<Link href="/dashboard" locale="fr">
Dashboard (French)
</Link>
</>
)
}as浏览器 URL 栏中显示的路径的可选装饰器。在 Next.js 9.5.3 之前,它用于动态路由,请查阅我们的 旧文档 以了解其工作原理。
当此路径与 href 中提供的路径不同时,将使用 旧文档 中所示的先前 href/as 行为。
onNavigate在客户端导航期间调用的事件处理程序。处理程序接收一个事件对象,其中包含一个 preventDefault() 方法,允许您在需要时取消导航。
import Link from 'next/link'
export default function Page() {
return (
<Link
href="/dashboard"
onNavigate={(e) => {
// Only executes during SPA navigation
console.log('Navigating...')
// Optionally prevent navigation
// e.preventDefault()
}}
>
Dashboard
</Link>
)
}import Link from 'next/link'
export default function Page() {
return (
<Link
href="/dashboard"
onNavigate={(e) => {
// Only executes during SPA navigation
console.log('Navigating...')
// Optionally prevent navigation
// e.preventDefault()
}}
>
Dashboard
</Link>
)
}须知:虽然
onClick和onNavigate看起来相似,但它们服务于不同的目的。onClick对所有点击事件执行,而onNavigate仅在客户端导航期间运行。一些主要区别:
- 当使用修饰键(
Ctrl/Cmd+ 点击)时,onClick执行而onNavigate不执行,因为 Next.js 会阻止新标签页的默认导航。- 外部 URL 不会触发
onNavigate,因为它仅适用于客户端和同源导航。- 带有
download属性的链接会与onClick一起工作,但不会与onNavigate一起工作,因为浏览器会将链接的 URL 视为下载。
以下示例演示了如何在不同场景中使用 <Link> 组件。
当链接到 动态路由段 时,您可以使用 模板字面量和插值 来生成链接列表。例如,要生成博客文章列表:
import Link from 'next/link'
interface Post {
id: number
title: string
slug: string
}
export default function PostList({ posts }: { posts: Post[] }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={`/blog/${post.slug}`}>{post.title}</Link>
</li>
))}
</ul>
)
}import Link from 'next/link'
export default function PostList({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={`/blog/${post.slug}`}>{post.title}</Link>
</li>
))}
</ul>
)
}您可以使用 usePathname() 来确定链接是否活动。例如,要为活动链接添加一个类,您可以检查当前 pathname 是否与链接的 href 匹配:
'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
export function Links() {
const pathname = usePathname()
return (
<nav>
<Link className={`link ${pathname === '/' ? 'active' : ''}`} href="/">
Home
</Link>
<Link
className={`link ${pathname === '/about' ? 'active' : ''}`}
href="/about"
>
About
</Link>
</nav>
)
}'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
export function Links() {
const pathname = usePathname()
return (
<nav>
<Link className={`link ${pathname === '/' ? 'active' : ''}`} href="/">
Home
</Link>
<Link
className={`link ${pathname === '/about' ? 'active' : ''}`}
href="/about"
>
About
</Link>
</nav>
)
}对于 动态路由段,使用模板字面量创建链接路径会非常方便。
例如,您可以生成一个指向动态路由 pages/blog/[slug].js 的链接列表
import Link from 'next/link'
function Posts({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={`/blog/${post.slug}`}>{post.title}</Link>
</li>
))}
</ul>
)
}import Link from 'next/link'
function Posts({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={`/blog/${post.slug}`}>{post.title}</Link>
</li>
))}
</ul>
)
}
export default Postsid如果您想在导航时滚动到特定的 id,您可以在 URL 中添加 # 锚点链接,或者直接将锚点链接传递给 href prop。这是可能的,因为 <Link> 会渲染成一个 <a> 元素。
<Link href="/dashboard#settings">Settings</Link>
// Output
<a href="/dashboard#settings">Settings</a>须知:
- 如果导航时 Page 在视口中不可见,Next.js 将滚动到该 Page。
Link 也可以接收一个 URL 对象,它会自动将其格式化以创建 URL 字符串:
import Link from 'next/link'
function Home() {
return (
<ul>
<li>
<Link
href={{
pathname: '/about',
query: { name: 'test' },
}}
>
About us
</Link>
</li>
<li>
<Link
href={{
pathname: '/blog/[slug]',
query: { slug: 'my-post' },
}}
>
Blog Post
</Link>
</li>
</ul>
)
}
export default Homeimport Link from 'next/link'
function Home() {
return (
<ul>
<li>
<Link
href={{
pathname: '/about',
query: { name: 'test' },
}}
>
About us
</Link>
</li>
<li>
<Link
href={{
pathname: '/blog/[slug]',
query: { slug: 'my-post' },
}}
>
Blog Post
</Link>
</li>
</ul>
)
}
export default Home上面的示例链接到:
/about?name=test/blog/my-post您可以使用 Node.js URL 模块文档 中定义的所有属性。
Link 组件的默认行为是将新的 URL push 到 history 堆栈中。您可以使用 replace prop 来防止添加新的条目,如下例所示:
import Link from 'next/link'
export default function Page() {
return (
<Link href="/about" replace>
About us
</Link>
)
}import Link from 'next/link'
export default function Page() {
return (
<Link href="/about" replace>
About us
</Link>
)
}import Link from 'next/link'
export default function Home() {
return (
<Link href="/about" replace>
About us
</Link>
)
}import Link from 'next/link'
export default function Home() {
return (
<Link href="/about" replace>
About us
</Link>
)
}Next.js 中 <Link> 的默认滚动行为是保持滚动位置,类似于浏览器处理前进和后退导航的方式。当您导航到一个新的 Page 时,只要该 Page 在视口中可见,滚动位置就会保持不变。
然而,如果该 Page 在视口中不可见,Next.js 将滚动到第一个 Page 元素的顶部。如果您想禁用此行为,可以将 scroll={false} 传递给 <Link> 组件,或者将 scroll: false 传递给 router.push() 或 router.replace()。
import Link from 'next/link'
export default function Page() {
return (
<Link href="/#hashid" scroll={false}>
Disables scrolling to the top
</Link>
)
}import Link from 'next/link'
export default function Page() {
return (
<Link href="/#hashid" scroll={false}>
Disables scrolling to the top
</Link>
)
}使用 router.push() 或 router.replace():
// useRouter
import { useRouter } from 'next/navigation'
const router = useRouter()
router.push('/dashboard', { scroll: false })Link 的默认行为是滚动到页面顶部。当定义了 hash 时,它将滚动到特定的 id,就像普通的 <a> 标签一样。为了防止滚动到顶部/hash,可以将 scroll={false} 添加到 Link:
import Link from 'next/link'
export default function Home() {
return (
<Link href="/#hashid" scroll={false}>
Disables scrolling to the top
</Link>
)
}import Link from 'next/link'
export default function Home() {
return (
<Link href="/#hashid" scroll={false}>
Disables scrolling to the top
</Link>
)
}通常使用 Proxy 进行身份验证或其他涉及将用户重写到不同页面的目的。为了使 <Link /> 组件通过 Proxy 正确预加载具有重写功能的链接,您需要告诉 Next.js 要显示哪个 URL 以及要预加载哪个 URL。这是为了避免不必要的 Proxy 获取,从而了解正确的预加载路由。
例如,如果您想提供一个 /dashboard 路由,该路由具有已验证和访客视图,您可以在 Proxy 中添加以下内容以将用户重定向到正确的页面:
import { NextResponse } from 'next/server'
export function proxy(request: Request) {
const nextUrl = request.nextUrl
if (nextUrl.pathname === '/dashboard') {
if (request.cookies.authToken) {
return NextResponse.rewrite(new URL('/auth/dashboard', request.url))
} else {
return NextResponse.rewrite(new URL('/public/dashboard', request.url))
}
}
}import { NextResponse } from 'next/server'
export function proxy(request) {
const nextUrl = request.nextUrl
if (nextUrl.pathname === '/dashboard') {
if (request.cookies.authToken) {
return NextResponse.rewrite(new URL('/auth/dashboard', request.url))
} else {
return NextResponse.rewrite(new URL('/public/dashboard', request.url))
}
}
}在这种情况下,您需要在 <Link /> 组件中使用以下代码:
'use client'
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed' // Your auth hook
export default function Page() {
const isAuthed = useIsAuthed()
const path = isAuthed ? '/auth/dashboard' : '/public/dashboard'
return (
<Link as="/dashboard" href={path}>
Dashboard
</Link>
)
}'use client'
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed' // Your auth hook
export default function Page() {
const isAuthed = useIsAuthed()
const path = isAuthed ? '/auth/dashboard' : '/public/dashboard'
return (
<Link as="/dashboard" href={path}>
Dashboard
</Link>
)
}'use client'
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed' // Your auth hook
export default function Home() {
const isAuthed = useIsAuthed()
const path = isAuthed ? '/auth/dashboard' : '/public/dashboard'
return (
<Link as="/dashboard" href={path}>
Dashboard
</Link>
)
}'use client'
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed' // Your auth hook
export default function Home() {
const isAuthed = useIsAuthed()
const path = isAuthed ? '/auth/dashboard' : '/public/dashboard'
return (
<Link as="/dashboard" href={path}>
Dashboard
</Link>
)
}须知:如果您正在使用 动态路由,您需要调整
as和hrefprops。例如,如果您有一个动态路由/dashboard/authed/[user],并希望通过 proxy 以不同方式呈现,您可以这样编写:<Link href={{ pathname: '/dashboard/authed/[user]', query: { user: username } }} as="/dashboard/[user]">Profile</Link>。
您可以使用 onNavigate prop 在满足某些条件时阻止导航,例如当表单有未保存的更改时。当您需要在应用程序中的多个组件之间阻止导航(例如在编辑表单时阻止任何链接导航)时,React Context 提供了一种清晰的方式来共享此阻止状态。首先,创建一个上下文来跟踪导航阻止状态:
'use client'
import { createContext, useState, useContext } from 'react'
interface NavigationBlockerContextType {
isBlocked: boolean
setIsBlocked: (isBlocked: boolean) => void
}
export const NavigationBlockerContext =
createContext<NavigationBlockerContextType>({
isBlocked: false,
setIsBlocked: () => {},
})
export function NavigationBlockerProvider({
children,
}: {
children: React.ReactNode
}) {
const [isBlocked, setIsBlocked] = useState(false)
return (
<NavigationBlockerContext.Provider value={{ isBlocked, setIsBlocked }}>
{children}
</NavigationBlockerContext.Provider>
)
}
export function useNavigationBlocker() {
return useContext(NavigationBlockerContext)
}'use client'
import { createContext, useState, useContext } from 'react'
export const NavigationBlockerContext = createContext({
isBlocked: false,
setIsBlocked: () => {},
})
export function NavigationBlockerProvider({ children }) {
const [isBlocked, setIsBlocked] = useState(false)
return (
<NavigationBlockerContext.Provider value={{ isBlocked, setIsBlocked }}>
{children}
</NavigationBlockerContext.Provider>
)
}
export function useNavigationBlocker() {
return useContext(NavigationBlockerContext)
}创建一个使用该上下文的表单组件:
'use client'
import { useNavigationBlocker } from '../contexts/navigation-blocker'
export default function Form() {
const { setIsBlocked } = useNavigationBlocker()
return (
<form
onSubmit={(e) => {
e.preventDefault()
setIsBlocked(false)
}}
onChange={() => setIsBlocked(true)}
>
<input type="text" name="name" />
<button type="submit">Save</button>
</form>
)
}'use client'
import { useNavigationBlocker } from '../contexts/navigation-blocker'
export default function Form() {
const { setIsBlocked } = useNavigationBlocker()
return (
<form
onSubmit={(e) => {
e.preventDefault()
setIsBlocked(false)
}}
onChange={() => setIsBlocked(true)}
>
<input type="text" name="name" />
<button type="submit">Save</button>
</form>
)
}创建一个阻止导航的自定义 Link 组件:
'use client'
import Link from 'next/link'
import { useNavigationBlocker } from '../contexts/navigation-blocker'
interface CustomLinkProps extends React.ComponentProps<typeof Link> {
children: React.ReactNode
}
export function CustomLink({ children, ...props }: CustomLinkProps) {
const { isBlocked } = useNavigationBlocker()
return (
<Link
onNavigate={(e) => {
if (
isBlocked &&
!window.confirm('You have unsaved changes. Leave anyway?')
) {
e.preventDefault()
}
}}
{...props}
>
{children}
</Link>
)
}'use client'
import Link from 'next/link'
import { useNavigationBlocker } from '../contexts/navigation-blocker'
export function CustomLink({ children, ...props }) {
const { isBlocked } = useNavigationBlocker()
return (
<Link
onNavigate={(e) => {
if (
isBlocked &&
!window.confirm('You have unsaved changes. Leave anyway?')
) {
e.preventDefault()
}
}}
{...props}
>
{children}
</Link>
)
}创建一个导航组件:
'use client'
import { CustomLink as Link } from './custom-link'
export default function Nav() {
return (
<nav>
<Link href="/">Home</Link>
<Link href="/about">About</Link>
</nav>
)
}'use client'
import { CustomLink as Link } from './custom-link'
export default function Nav() {
return (
<nav>
<Link href="/">Home</Link>
<Link href="/about">About</Link>
</nav>
)
}最后,在根布局中用 NavigationBlockerProvider 包装您的应用程序,并在页面中使用这些组件:
import { NavigationBlockerProvider } from './contexts/navigation-blocker'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
<NavigationBlockerProvider>{children}</NavigationBlockerProvider>
</body>
</html>
)
}import { NavigationBlockerProvider } from './contexts/navigation-blocker'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<NavigationBlockerProvider>{children}</NavigationBlockerProvider>
</body>
</html>
)
}然后,在您的页面中使用 Nav 和 Form 组件:
import Nav from './components/nav'
import Form from './components/form'
export default function Page() {
return (
<div>
<Nav />
<main>
<h1>Welcome to the Dashboard</h1>
<Form />
</main>
</div>
)
}import Nav from './components/nav'
import Form from './components/form'
export default function Page() {
return (
<div>
<Nav />
<main>
<h1>Welcome to the Dashboard</h1>
<Form />
</main>
</div>
)
}当用户尝试使用 CustomLink 导航离开,而表单有未保存的更改时,系统会提示他们确认是否离开。
| 版本号 | 更改 |
|---|---|
v15.4.0 | 添加 auto 作为默认 prefetch 行为的别名。 |
v15.3.0 | 添加 onNavigate API。 |
v13.0.0 | 不再需要子 <a> 标签。提供了 codemod 来自动更新您的代码库。 |
v10.0.0 | 指向动态路由的 href props 会自动解析,不再需要 as prop。 |
v8.0.0 | 改进了预加载性能。 |
v1.0.0 | 引入 next/link。 |