next/link

示例

再继续之前,我们建议先阅读 路由简介

通过 Link 组件可以启用客户端的路由切换。Link 组件导出(export)自 next/link

例如,假定 pages 目录下包含以下文件:

  • pages/index.js
  • pages/about.js
  • pages/blog/[slug].js

我们可以像下面这样链接到每个页面:

import Link from 'next/link'

function Home() {
  return (
    <ul>
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/about">
          <a>About Us</a>
        </Link>
      </li>
      <li>
        <Link href="/blog/hello-world">
          <a>Blog Post</a>
        </Link>
      </li>
    </ul>
  )
}

export default Home

Link 组件可以接受以下属性:

  • href - 导航的目标路径或 URL。这是唯一需要的属性(prop)
  • as - 可选的路径装饰符,用于显示在浏览器的地址栏中。在 Next.js 9.5.3 版本之前,该属性用于动态路由,请查看我们 先前的文档 以了解其工作原理。注意:when this path differs from the one provided in href the previous href/as behavior is used as shown in the previous docs.
  • passHref - 强制 Linkhref 属性传递给其子元素。默认为值 false
  • prefetch - 在后台预取目标页面。默认值为 true。处于视口(viewport)中(初始或滚动后)的任何 <Link /> 都将被预加载。通过设置 prefetch={false} 可以禁止页面预取。当 prefetch 被设置为 false 时,鼠标悬停在 <Link /> 上时仍然会触发预取。使用 静态生成 的页面(pages)将预加载存有数据的 JSON 文件,以实现更快的页面切换。预取功能只在生产环境中开启。
  • replace - 替换当前的 history 状态,而不是在 history 堆栈中添加新的 url。默认值为 false
  • scroll - 导航到新页面之后滚动到页面顶部。默认值为 true
  • shallow - 更新当前页面的路径,并无需重新运行 getStaticPropsgetServerSidePropsgetInitialProps。默认值为 false
  • locale - 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.

If the route has dynamic segments

There is nothing to do when linking to a dynamic route, including catch all routes, since Next.js 9.5.3 (for older versions check our previous docs). However, it can become quite common and handy to use interpolation or an URL Object to generate the link.

For example, the dynamic route pages/blog/[slug].js will match the following link:

import Link from 'next/link'

function Posts({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>
          <Link href={`/blog/${encodeURIComponent(post.slug)}`}>
            <a>{post.title}</a>
          </Link>
        </li>
      ))}
    </ul>
  )
}

export default Posts

If the child is a custom component that wraps an <a> tag

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 }) {
  // Must add passHref to Link
  return (
    <Link href={href} passHref>
      <RedLink>{name}</RedLink>
    </Link>
  )
}

export default NavLink
  • If you’re using emotion’s JSX pragma feature (@jsx jsx), you must use passHref even if you use an <a> tag directly.
  • The component should support onClick property to trigger navigation correctly

If the child is a functional component

If the child of Link is a functional component, in addition to using passHref, you must wrap the component in React.forwardRef:

import Link from 'next/link'

// `onClick`, `href`, and `ref` need to be passed to the DOM element
// for proper handling
const MyButton = React.forwardRef(({ onClick, href }, ref) => {
  return (
    <a href={href} onClick={onClick} ref={ref}>
      Click Me
    </a>
  )
})

function Home() {
  return (
    <Link href="/about" passHref>
      <MyButton />
    </Link>
  )
}

export default Home

With URL Object

Link can also receive a URL object and it will automatically format it to create the URL string. Here's how to do it:

import Link from 'next/link'

function Home() {
  return (
    <ul>
      <li>
        <Link
          href={{
            pathname: '/about',
            query: { name: 'test' },
          }}
        >
          <a>About us</a>
        </Link>
      </li>
      <li>
        <Link
          href={{
            pathname: '/blog/[slug]',
            query: { slug: 'my-post' },
          }}
        >
          <a>Blog Post</a>
        </Link>
      </li>
    </ul>
  )
}

export default Home

The above example has a link to:

  • A predefined route: /about?name=test
  • A dynamic route: /blog/my-post

You can use every property as defined in the Node.js URL module documentation.

Replace the URL instead of push

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:

<Link href="/about" replace>
  <a>About us</a>
</Link>

Disable scrolling to the top of the page

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:

<Link href="/?counter=10" scroll={false}>
  <a>Disables scrolling to the top</a>
</Link>