You need to enable JavaScript to run this app. React实现首页滚动时自动跳转定位至对应组件的方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

React实现首页滚动时自动跳转定位至对应组件的方法咨询

实现滚动自动定位组件需要掌握的知识点
  • HTML原生锚点与DOM定位属性:理解元素id属性、offsetTop、getBoundingClientRect()等获取元素位置的原生API,是所有定位效果的基础
  • React ref 与 useRef 钩子:函数组件中不能直接操作DOM,需要通过useRef获取目标组件对应DOM节点的引用
  • 滚动事件监听与节流优化:掌握window.scroll事件的绑定/卸载逻辑,以及节流函数的使用,避免滚动事件高频触发导致性能问题
  • scrollIntoView API:原生提供的滚动定位方法,支持配置平滑滚动、定位位置等参数,是实现自动跳转的核心方法
  • React 基础钩子使用:useEffect用来在组件挂载时绑定监听、卸载时移除监听,避免内存泄漏
可直接运行的修改后代码
import React, { useRef, useEffect, useCallback } from 'react'
import {Header} from 'components/Header'
import {Title} from 'style/CommonStyle';

// 节流函数,避免滚动事件频繁触发逻辑
const throttle = (func, delay) => {
  let lastTime = 0
  return (...args) => {
    const now = Date.now()
    if (now - lastTime >= delay) {
      func.apply(this, args)
      lastTime = now
    }
  }
}

const Comp1 = () => {
  return (
    <div style={{height: '100vh'}}> {/* 此处可替换为你实际的组件高度 */}
      <Title>Title of Comp1</Title>
      ...
    </div>
  )
}
const Comp2 = () => {
  return (
    <div style={{height: '100vh'}}> {/* 此处可替换为你实际的组件高度 */}
      <Title>Title of Comp2</Title>
      ...
    </div>
  )
}

const MainPage = () => {
  // 给两个组件创建DOM引用
  const comp1Ref = useRef(null)
  const comp2Ref = useRef(null)
  // 标记是否正在自动滚动,避免和用户手动滚动冲突
  const isScrolling = useRef(false)

  const handleScroll = useCallback(throttle(() => {
    if (isScrolling.current) return
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop
    const comp1Top = comp1Ref.current.offsetTop
    const comp2Top = comp2Ref.current.offsetTop
    const windowHeight = window.innerHeight

    // 滚动距离超过Comp1一半高度时,自动定位到Comp2
    if (scrollTop > comp1Top + windowHeight / 2) {
      isScrolling.current = true
      comp2Ref.current.scrollIntoView({ behavior: 'smooth' })
      // 滚动结束后重置标记,时长可根据平滑滚动速度调整
      setTimeout(() => {
        isScrolling.current = false
      }, 1000)
    // 滚动距离低于Comp2一半高度时,自动定位回Comp1
    } else if (scrollTop < comp2Top - windowHeight / 2) {
      isScrolling.current = true
      comp1Ref.current.scrollIntoView({ behavior: 'smooth' })
      setTimeout(() => {
        isScrolling.current = false
      }, 1000)
    }
  }, 200), [])

  useEffect(() => {
    window.addEventListener('scroll', handleScroll)
    return () => {
      window.removeEventListener('scroll', handleScroll)
    }
  }, [handleScroll])

  return (
    <div>
      <Header />
      {/* 把ref绑定到组件外层容器上 */}
      <div ref={comp1Ref}>
        <Comp1 />
      </div>
      <div ref={comp2Ref}>
        <Comp2 />
      </div>
    </div>
  )
}

export default MainPage
补充说明

如果组件数量不固定,可以把所有组件的ref存入数组统一遍历判断,无需单独编写每个组件的定位逻辑。不需要平滑滚动的话,删除scrollIntoView配置里的behavior: 'smooth'即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 06:54:07