react 元素触底hooks封装

useScrollHitBottom.ts

typescript 复制代码
import React, { useEffect, useCallback, useMemo } from 'react'

interface IProps {
  loading: boolean
  onHitBottom: () => void
  container?: HTMLElement | React.RefObject<HTMLElement> | Window | null // 支持多种容器类型
  offset?: number // 触底偏移量
}

const useScrollHitBottom = ({
  loading,
  onHitBottom,
  container = window,
  offset = 100, // 默认距离底部100px触发
}: IProps) => {
  const targetContainer = useMemo(() => {
    if (!container) return window
    return 'current' in container ? container.current : container
  }, [container])

  // 2. 滚动事件回调(兼容所有容器)
  const handleScroll = useCallback(() => {
    if (!targetContainer) return

    // 3. 统一获取滚动参数(区分window和普通DOM)
    let scrollTop: number
    let scrollHeight: number
    let clientHeight: number

    if (targetContainer === window) {
      scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
      clientHeight = document.documentElement.clientHeight || window.innerHeight
    } else {
      scrollTop = targetContainer.scrollTop
      scrollHeight = targetContainer.scrollHeight
      clientHeight = targetContainer.clientHeight
    }

    const isHitBottom = scrollTop + clientHeight >= scrollHeight - offset
    const hasScrollBar = scrollHeight > clientHeight

    if (isHitBottom && hasScrollBar && !loading) {
      onHitBottom()
    }
  }, [targetContainer, loading, onHitBottom, offset])

  useEffect(() => {
    if (!targetContainer) return

    // 绑定滚动事件(window/document/DOM 都支持 addEventListener)
    const eventTarget = targetContainer === window ? document : targetContainer
    eventTarget.addEventListener('scroll', handleScroll)

    return () => {
      eventTarget.removeEventListener('scroll', handleScroll)
    }
  }, [targetContainer, handleScroll])
}

export default useScrollHitBottom

使用

javascript 复制代码
import { RESUME_CID } from '@/constant/resume'
import { Header, Keywords, Template, Promotion, Search, Menu, Resume } from './components'
import style from './index.module.scss'
import { useScrollHitBottom } from '@/hooks'
import { useRef } from 'react'
import { useAggregationStore } from '@/store/aggregation'
import { useParams } from 'react-router'

const AggregationV2 = () => {
  const { cid } = useParams()

  const divref = useRef<HTMLDivElement>(null)
  const [loading, setLoading] = useState(false)
  const [hitBottom, setHitBottom] = useState(false)

  const onHitBottom = () => {
    if (!loading) {
      console.log('触底了')
      setHitBottom(true)
    }
  }
  useScrollHitBottom({ loading, onHitBottom, container: divref.current })

  return (
    <div className={style.aggregationV2} ref={divref}>
      <div className={style.containerTop}>
        <Menu />
        <div className={style.containerTopBox}>
          <Header />
          <Search />
          <Keywords />
        </div>
      </div>
      {Number(cid) === RESUME_CID ? (
        <div className={style.container}>
          <Resume />
        </div>
      ) : (
        <div className={style.container}>
          <Promotion />
          <Template />
        </div>
      )}
    </div>
  )
}

export default AggregationV2

  
相关推荐
To_OC4 小时前
LC 51 N 皇后:我以为难的是回溯,结果栽在了对角线下标
javascript·算法·leetcode
不好听6135 小时前
从一行 JSX 到屏幕像素:前端开发者必须懂的浏览器渲染管线
前端
恒拓高科WorkPlus5 小时前
企业级内网即时通讯建设模型:BeeWorks内网IM四层架构
前端
前端小李子5 小时前
前端环境变量裸奔?我用 EnvShield 给它穿了件防弹衣
前端
youtootech5 小时前
HarmonyOS《柚兔学伴》项目实战25-我的页面、Web 嵌入与项目总结
前端·华为·harmonyos
小林ixn6 小时前
从零到一理解 React 父子组件通信:手写一个 Todo 应用带你彻底搞懂单向数据流
前端·javascript·react.js
醇氧7 小时前
CountDownLatch / CyclicBarrier / Semaphore 面试高频问答清单
前端·面试·职场和发展
窝子面8 小时前
手搓最简前后端协作-node
javascript·数据库
qetfw9 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具