You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中从导航栏跳转页面后,如何自动滚动到指定组件?

在Next.js中实现跳转后自动滚动到指定组件

这里分两种常见路由场景给出实用解决方案:

方案1:锚点链接(最简单直接)

步骤1:修改导航栏的Link组件

在跳转地址后添加锚点标识,比如你要滚动到的目标组件id为rahim-detail,就这么写:

<Link className="dropdown-item" href="/about-rahim#rahim-detail">Know Rahim</Link>

步骤2:给目标组件绑定对应id

在about-rahim页面中,找到需要滚动到的组件,给它加上匹配的id属性:

// about-rahim页面内的目标组件
<section id="rahim-detail">
  {/* 组件内容 */}
</section>

注意事项

  • Next.js 13+的App Router默认支持锚点自动滚动,无需额外配置;
  • 若使用Pages Router,确保next.config.js未禁用默认滚动行为(默认是开启状态):
module.exports = {
  scrollBehavior: 'auto' // 保持默认即可,无需手动修改
}

方案2:手动控制滚动(适配复杂场景)

如果锚点方式满足不了需求(比如滚动到动态生成的组件、需要自定义滚动动画),可以结合路由钩子和原生滚动API实现:

针对Pages Router

在about-rahim页面中编写逻辑:

import { useRouter } from 'next/router'
import { useEffect } from 'react'

export default function AboutRahim() {
  const router = useRouter()

  useEffect(() => {
    // 从URL中提取锚点部分
    const { hash } = router
    if (hash) {
      const targetElement = document.querySelector(hash)
      if (targetElement) {
        // 平滑滚动到目标元素
        targetElement.scrollIntoView({ behavior: 'smooth' })
      }
    }
  }, [router])

  return (
    <div>
      {/* 其他页面组件 */}
      <section id="rahim-detail">目标组件</section>
    </div>
  )
}

针对App Router(Next.js 13+)

在about-rahim/page.js中编写逻辑:

import { usePathname } from 'next/navigation'
import { useEffect } from 'react'

export default function AboutRahim() {
  const pathname = usePathname()

  useEffect(() => {
    // 解析当前URL的锚点部分
    const hash = window.location.hash
    if (hash) {
      const targetElement = document.querySelector(hash)
      if (targetElement) {
        targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' })
      }
    }
  }, [pathname])

  return (
    <div>
      {/* 其他页面组件 */}
      <section id="rahim-detail">目标组件</section>
    </div>
  )
}

额外技巧:自定义滚动偏移

如果需要滚动时避开顶部导航栏(比如固定导航栏遮挡目标组件),可以手动调整滚动位置:

// 滚动时距离顶部预留50px空隙
window.scrollTo({
  top: targetElement.offsetTop - 50,
  behavior: 'smooth'
})

内容的提问来源于stack exchange,提问作者atq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 22:42:29