链接
¥Link
<Link>
是一个 React 组件,它扩展了 HTML <a>
元素以提供 prefetching 和路由之间的客户端导航。这是在 Next.js 中的路由之间导航的主要方式。
¥<Link>
is a React component that extends the HTML <a>
element to provide prefetching and client-side navigation between routes. It is the primary way to navigate between routes in Next.js.
基本用法:
¥Basic usage:
import Link from 'next/link'
export default function Home() {
return <Link href="/dashboard">Dashboard</Link>
}
参考
¥Reference
可以将以下 props 传递给 <Link>
组件:
¥The following props can be passed to the <Link>
component:
Prop | 示例 | 类型 | 必需 |
---|---|---|---|
href | href="/dashboard" | 字符串或对象 | 是 |
replace | replace={false} | 布尔值 | * |
scroll | scroll={false} | 布尔值 | * |
prefetch | prefetch={false} | 布尔值 | * |
legacyBehavior | legacyBehavior={true} | 布尔值 | * |
passHref | passHref={true} | 布尔值 | * |
shallow | shallow={false} | 布尔值 | * |
locale | locale="fr" | 字符串或布尔值 | * |
onNavigate | onNavigate={(e) => {}} | 函数 | * |
需要了解:
<a>
标签属性(例如className
或target="_blank"
)可以作为 props 添加到<Link>
中,并将传递到底层<a>
元素。¥Good to know:
<a>
tag attributes such asclassName
ortarget="_blank"
can be added to<Link>
as props and will be passed to the underlying<a>
element.
href
(必需的)
¥href
(required)
要导航到的路径或 URL。
¥The path or URL to navigate to.
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。
¥Defaults to false
. When true
, next/link
will replace the current history state instead of adding a new URL into the browser's history stack.
import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" replace>
Dashboard
</Link>
)
}
scroll
默认为 true
。Next.js 中 <Link>
的默认滚动行为是保持滚动位置,类似于浏览器处理前后导航的方式。当你导航到新的 页面 时,只要页面在视口中可见,滚动位置就会保持不变。但是,如果页面在视口中不可见,Next.js 将滚动到第一个页面元素的顶部。
¥Defaults to true
. The default scrolling behavior of <Link>
in Next.js is to maintain scroll position, similar to how browsers handle back and forwards navigation. When you navigate to a new Page, scroll position will stay the same as long as the Page is visible in the viewport. However, if the Page is not visible in the viewport, Next.js will scroll to the top of the first Page element.
当 scroll = {false}
时,Next.js 将不会尝试滚动到第一个 Page 元素。
¥When scroll = {false}
, Next.js will not attempt to scroll to the first Page element.
需要了解:Next.js 在管理滚动行为之前检查
scroll: false
。如果启用了滚动,它会识别导航的相关 DOM 节点并检查每个顶层元素。所有不可滚动的元素和没有渲染 HTML 的元素都将被绕过,这包括粘性或固定定位的元素,以及不可见的元素(例如使用getBoundingClientRect
计算的元素)。Next.js 然后继续遍历同级元素,直到它识别出在视口中可见的可滚动元素。¥Good to know: Next.js checks if
scroll: false
before managing scroll behavior. If scrolling is enabled, it identifies the relevant DOM node for navigation and inspects each top-level element. All non-scrollable elements and those without rendered HTML are bypassed, this includes sticky or fixed positioned elements, and non-visible elements such as those calculated withgetBoundingClientRect
. Next.js then continues through siblings until it identifies a scrollable element that is visible in the viewport.
import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" scroll={false}>
Dashboard
</Link>
)
}
prefetch
当 <Link />
组件进入用户的视口(最初或通过滚动)时,会发生预取。Next.js 会在后台预取并加载链接的路由(用 href
表示)和数据,以提高客户端导航的性能。预取仅在生产中启用。
¥Prefetching happens when a <Link />
component enters the user's viewport (initially or through scroll). Next.js prefetches and loads the linked route (denoted by the href
) and data in the background to improve the performance of client-side navigation's. Prefetching is only enabled in production.
可以将以下值传递给 prefetch
prop:
¥The following values can be passed to the prefetch
prop:
true
(默认):完整的路由及其数据将被预取。¥
true
(default): The full route and its data will be prefetched.false
:进入视口时不会进行预取,但鼠标悬停时会发生。如果你还想完全移除悬停时的数据获取,请考虑使用<a>
标签或 逐步采用 应用路由,它们也可以禁用悬停时的预获取。¥
false
: Prefetching will not happen when entering the viewport, but will happen on hover. If you want to completely remove fetching on hover as well, consider using an<a>
tag or incrementally adopting the App Router, which enables disabling prefetching on hover too.
import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" prefetch={false}>
Dashboard
</Link>
)
}
legacyBehavior
警告:
legacyBehavior
属性将在 Next.js v16 中被移除。要采用新的<Link>
行为,请删除用作<Link>
子项的所有<a>
标签。代码模式可用 可帮助你自动升级代码库。¥Warning: The
legacyBehavior
prop will be removed in Next.js v16. To adopt the new<Link>
behavior, remove any<a>
tags used as children of<Link>
. A codemod is available to help you automatically upgrade your codebase.
从版本 13 开始,<a>
元素不再需要作为 <Link>
组件的子元素。如果出于兼容性原因你仍然需要旧的行为,你可以添加 legacyBehavior
属性。
¥Since version 13, an <a>
element is no longer required as a child of the <Link>
component. If you still need the old behavior for compatibility reasons, you can add the legacyBehavior
prop.
需要了解:当
legacyBehavior
未设置为true
时,所有anchor
标签属性都可以传递给next/link
,例如className
、onClick
等。¥Good to know: when
legacyBehavior
is not set totrue
, allanchor
tag properties can be passed tonext/link
as well such as,className
,onClick
, etc.
passHref
强制 Link
将 href
属性发送给其子级。默认为 false
。更多信息请参阅 传递函数式组件 示例。
¥Forces Link
to send the href
property to its child. Defaults to false
. See the passing a functional component example for more information.
shallow
更新当前页面的路径,无需重新运行 getStaticProps
、getServerSideProps
或 getInitialProps
。默认为 false
。
¥Update the path of the current page without rerunning getStaticProps
, getServerSideProps
or getInitialProps
. Defaults to false
.
import Link from 'next/link'
export default function Home() {
return (
<Link href="/dashboard" shallow={false}>
Dashboard
</Link>
)
}
locale
活动语言环境将自动添加到前面。locale
允许提供不同的语言环境。当 false
和 href
必须包含语言环境时,默认行为将被禁用。
¥The active locale is automatically prepended. locale
allows for providing a different locale. When false
href
has to include the locale as the default behavior is disabled.
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>
</>
)
}
onNavigate
客户端导航期间调用的事件处理程序。处理程序接收包含 preventDefault()
方法的事件对象,允许你根据需要取消导航。
¥An event handler called during client-side navigation. The handler receives an event object that includes a preventDefault()
method, allowing you to cancel the navigation if needed.
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
仅在客户端导航期间运行。一些主要区别:¥Good to know: While
onClick
andonNavigate
may seem similar, they serve different purposes.onClick
executes for all click events, whileonNavigate
only runs during client-side navigation. Some key differences:
当使用修饰键(
Ctrl
/Cmd
+ 点击)时,onClick
会执行,但onNavigate
不会执行,因为 Next.js 会阻止新标签页的默认导航。¥When using modifier keys (
Ctrl
/Cmd
+ Click),onClick
executes butonNavigate
doesn't since Next.js prevents default navigation for new tabs.外部 URL 不会触发
onNavigate
,因为它仅适用于客户端和同源导航。¥External URLs won't trigger
onNavigate
since it's only for client-side and same-origin navigations.带有
download
属性的链接可以在onClick
中使用,但不可以在onNavigate
中使用,因为浏览器会将链接的 URL 视为下载。¥Links with the
download
attribute will work withonClick
but notonNavigate
since the browser will treat the linked URL as a download.
示例
¥Examples
以下示例演示了如何在不同场景中使用 <Link>
组件。
¥The following examples demonstrate how to use the <Link>
component in different scenarios.
链接到动态路由段
¥Linking to dynamic route segments
对于 动态路由段,使用模板文字来创建链接的路径会很方便。
¥For dynamic route segments, it can be handy to use template literals to create the link's path.
例如,你可以生成指向动态路由 pages/blog/[slug].js
的链接列表。
¥For example, you can generate a list of links to the dynamic route 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>
)
}
如果子组件是封装 <a>
标签的自定义组件
¥If the child is a custom component that wraps an <a>
tag
如果 Link
的子组件是封装 <a>
标签的自定义组件,则必须将 passHref
添加到 Link
。如果你使用像 styled-components 这样的库,这是必要的。如果没有这个,<a>
标签将不会有 href
属性,这会损害你网站的可访问性并可能影响 SEO。如果你使用 ESLint,则有一个内置规则 next/link-passhref
可确保正确使用 passHref
。
¥If the child of Link
is a custom component that wraps an <a>
tag, you must add passHref
to Link
. This is necessary if you’re using libraries like styled-components. Without this, the <a>
tag will not have the href
attribute, which hurts your site's accessibility and might affect SEO. If you're using ESLint, there is a built-in rule next/link-passhref
to ensure correct usage of passHref
.
import Link from 'next/link'
import styled from 'styled-components'
// This creates a custom component that wraps an <a> tag
const RedLink = styled.a`
color: red;
`
function NavLink({ href, name }) {
return (
<Link href={href} passHref legacyBehavior>
<RedLink>{name}</RedLink>
</Link>
)
}
export default NavLink
如果你使用 emotion 的 JSX pragma 功能 (
@jsx jsx
),则即使直接使用<a>
标记,也必须使用passHref
。¥If you’re using emotion’s JSX pragma feature (
@jsx jsx
), you must usepassHref
even if you use an<a>
tag directly.组件应支持
onClick
属性以正确触发导航。¥The component should support
onClick
property to trigger navigation correctly.
嵌套功能组件
¥Nesting a functional component
如果 Link
的子组件是功能组件,除了使用 passHref
和 legacyBehavior
之外,还必须将该组件封装在 React.forwardRef
中:
¥If the child of Link
is a functional component, in addition to using passHref
and legacyBehavior
, you must wrap the component in React.forwardRef
:
import Link from 'next/link'
import React from 'react'
// Define the props type for MyButton
interface MyButtonProps {
onClick?: React.MouseEventHandler<HTMLAnchorElement>
href?: string
}
// Use React.ForwardRefRenderFunction to properly type the forwarded ref
const MyButton: React.ForwardRefRenderFunction<
HTMLAnchorElement,
MyButtonProps
> = ({ onClick, href }, ref) => {
return (
<a href={href} onClick={onClick} ref={ref}>
Click Me
</a>
)
}
// Use React.forwardRef to wrap the component
const ForwardedMyButton = React.forwardRef(MyButton)
export default function Home() {
return (
<Link href="/about" passHref legacyBehavior>
<ForwardedMyButton />
</Link>
)
}
传递 URL 对象
¥Passing a URL Object
Link
也可以接收 URL 对象,并会自动格式化该对象以创建 URL 字符串:
¥Link
can also receive a URL object and it will automatically format it to create the URL string:
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 Home
以上示例包含指向以下链接:
¥The above example has a link to:
预定义路由:
/about?name=test
¥A predefined route:
/about?name=test
A 动态路由:
/blog/my-post
¥A dynamic route:
/blog/my-post
你可以使用 Node.js URL 模块文档 中定义的每个属性。
¥You can use every property as defined in the Node.js URL module documentation.
替换 URL 而不是推送
¥Replace the URL instead of push
Link
组件的默认行为是将 push
新 URL 放入 history
堆栈中。你可以使用 replace
属性来防止添加新条目,如下例所示:
¥The default behavior of the Link
component is to push
a new URL into the history
stack. You can use the replace
prop to prevent adding a new entry, as in the following example:
import Link from 'next/link'
export default function Home() {
return (
<Link href="/about" replace>
About us
</Link>
)
}
禁用滚动到页面顶部
¥Disable scrolling to the top of the page
Link
的默认行为是滚动到页面顶部。当定义了哈希值时,它将滚动到特定的 ID,就像普通的 <a>
标签一样。为防止滚动到顶部/井号,可将 scroll={false}
添加到 Link
中:
¥The default behavior of Link
is to scroll to the top of the page. When there is a hash defined it will scroll to the specific id, like a normal <a>
tag. To prevent scrolling to the top / hash scroll={false}
can be added to Link
:
import Link from 'next/link'
export default function Home() {
return (
<Link href="/#hashid" scroll={false}>
Disables scrolling to the top
</Link>
)
}
在中间件中预取链接
¥Prefetching links in Middleware
通常将 中间件 用于身份验证或涉及将用户重写到不同页面的其他目的。为了让 <Link />
组件通过中间件重写正确地预取链接,你需要告诉 Next.js 要显示的 URL 和要预取的 URL。这是为了避免不必要的中间件获取来了解预取的正确路径。
¥It's common to use Middleware for authentication or other purposes that involve rewriting the user to a different page. In order for the <Link />
component to properly prefetch links with rewrites via Middleware, you need to tell Next.js both the URL to display and the URL to prefetch. This is required to avoid un-necessary fetches to middleware to know the correct route to prefetch.
例如,如果你想要提供具有经过身份验证和访问者视图的 /dashboard
路由,则可以在中间件中添加以下内容以将用户重定向到正确的页面:
¥For example, if you want to serve a /dashboard
route that has authenticated and visitor views, you can add the following in your Middleware to redirect the user to the correct page:
import { NextResponse } from 'next/server'
export function middleware(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))
}
}
}
在这种情况下,你需要在 <Link />
组件中使用以下代码:
¥In this case, you would want to use the following code in your <Link />
component:
'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>
)
}
阻止导航
¥Blocking navigation
你可以使用 onNavigate
属性在满足某些条件时阻止导航,例如当表单中有未保存的更改时。当你需要阻止应用中跨多个组件的导航时(例如,在编辑表单时阻止从任何链接导航),React Context 提供了一种简洁的方式来共享此阻止状态。首先,创建一个上下文来跟踪导航阻塞状态:
¥You can use the onNavigate
prop to block navigation when certain conditions are met, such as when a form has unsaved changes. When you need to block navigation across multiple components in your app (like preventing navigation from any link while a form is being edited), React Context provides a clean way to share this blocking state. First, create a context to track the navigation blocking state:
'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)
}
创建一个使用上下文的表单组件:
¥Create a form component that uses the context:
'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 组件:
¥Create a custom Link component that blocks navigation:
'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>
)
}
创建导航组件:
¥Create a navigation component:
'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
封装你的应用,并将其添加到根布局中,并在页面中使用这些组件:
¥Finally, wrap your app with the NavigationBlockerProvider
in the root layout and use the components in your page:
import { NavigationBlockerProvider } from './contexts/navigation-blocker'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
<NavigationBlockerProvider>{children}</NavigationBlockerProvider>
</body>
</html>
)
}
然后,在你的页面中使用 Nav
和 Form
组件:
¥Then, use the Nav
and Form
components in your page:
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
离开表单且表单中有未保存的更改时,系统会提示他们在离开前进行确认。
¥When a user tries to navigate away using CustomLink
while the form has unsaved changes, they'll be prompted to confirm before leaving.
版本历史记录
¥Version history
版本 | 更改 |
---|---|
v15.3.0 | 添加 onNavigate API |
v13.0.0 | 不再需要子 <a> 标签。提供 codemod 来自动更新你的代码库。 |
v10.0.0 | 指向动态路由的 href 属性会自动解析,不再需要 as 属性。 |
v8.0.0 | 改进了预取性能。 |
v1.0.0 | next/link 已引入。 |