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

React中如何通过函数跳转到携带指定id的div元素

useNavigate 只负责修改路由状态,不会触发浏览器原生的锚点滚动逻辑,所以直接传hash值不会定位到对应元素,可直接用以下方案实现:

方案1:零依赖原生实现(最推荐,适配绝大多数场景)

不需要额外引入路由相关插件,校验完id存在后直接调用原生DOM的滚动方法即可,同时可以同步更新URL hash不触发刷新:

const jumpToElement = (id_string) => {
  const targetElement = document.getElementById(id_string)
  if (targetElement) {
    // 滚动到目标元素位置,behavior设为smooth是平滑滚动,不需要可改为auto
    targetElement.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
    // 可选:同步更新地址栏的hash,不会触发页面重渲染
    window.history.replaceState(null, '', `#${id_string}`)
  }
}

直接在你的校验逻辑通过后调用这个方法就行,不需要走useNavigate。

方案2:适配React Router的全局统一处理

如果你希望所有带hash的路由跳转都自动触发定位,不需要每个跳转逻辑单独写滚动代码,可以在根路由/布局组件中添加hash监听逻辑:

import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'

function RootLayout() {
  const location = useLocation()

  useEffect(() => {
    // 监听路由变化,存在hash时自动滚动到对应元素
    if (location.hash) {
      const targetId = location.hash.slice(1)
      const targetElement = document.getElementById(targetId)
      targetElement?.scrollIntoView({ behavior: 'smooth', block: 'start' })
    }
  }, [location])

  return (
    {/* 你的页面布局、路由出口代码 */}
  )
}

添加这段逻辑后,你之前写的navigate('#' + id_string)就能正常触发定位了。

注意事项

  • 如果目标id对应的元素是异步渲染的(比如依赖接口返回数据才会挂载),需要等元素挂载完成后再执行滚动逻辑,否则会拿不到DOM元素,可在数据加载完成的回调/副作用中触发滚动。
  • react-router-hash-link 本身是封装给声明式链接(即<HashLink>组件点击场景)用的,不适合函数式触发跳转的场景,没必要强行使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 02:54:40