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

  
相关推荐
onebyte8bits6 分钟前
前端国际化(i18n)体系设计与工程化落地
前端·国际化·i18n·工程化
C澒15 分钟前
前端分层架构实战:DDD 与 Clean Architecture 在大型业务系统中的落地路径与项目实践
前端·架构·系统架构·前端框架
BestSongC19 分钟前
行人摔倒检测系统 - 前端文档(1)
前端·人工智能·目标检测
lbb 小魔仙23 分钟前
【HarmonyOS实战】React Native 鸿蒙版实战:Calendar 日历组件完全指南
react native·react.js·harmonyos
0思必得01 小时前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice1 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶3601 小时前
php怎么实现订单接口状态轮询(二)
前端·php·接口
大橙子额2 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
WooaiJava3 小时前
AI 智能助手项目面试技术要点总结(前端部分)
javascript·大模型·html5
LYFlied3 小时前
从 Vue 到 React,再到 React Native:资深前端开发者的平滑过渡指南
vue.js·react native·react.js