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

  
相关推荐
皮蛋瘦肉粥_1211 小时前
pink老师-jsAPIS-day1
javascript·apis
ByteCraze1 小时前
CDN 引入 与 npm 引入的区别
前端·npm·node.js
crary,记忆1 小时前
PNPM 和 NPM
前端·学习·npm·node.js
爱吃无爪鱼1 小时前
04-npm 与 Bun 快速入门实战指南
前端·vue.js·react.js·npm·sass
灵犀坠1 小时前
前端面试&项目实战核心知识点总结(Vue3+Pinia+UniApp+Axios)
前端·javascript·css·面试·职场和发展·uni-app·html
GISer_Jing1 小时前
SSE Conf大会分享——大模型驱动的智能 可视分析与故事叙述
前端·人工智能·信息可视化
Lovely Ruby1 小时前
前端er Go-Frame 的学习笔记:实现 to-do 功能(一)
前端·学习·golang
fruge1 小时前
Vue3 与 Vue2 核心差异:响应式原理、生命周期及迁移方案
前端·javascript·vue.js