QT开发中文网

const handleScroll = () => { const scrollTop: any = document.getElementById('history-scroll')?.scrollTop const clientHeight: any = document.getElementById('history-scroll')?.clientHeight const scrollHeight: any = document.getElementByI...

可以将该代码块封装成一个公用的方法,以便在其他组件中复用。以下是将其封装为一个可调用的函数示例:

import { useEffect, useState } from 'react';

const useInfiniteScroll = (scrollContainerId, fetchDataCallback) => {
  const [isLoadComplete, setIsLoadComplete] = useState(false);
  const [num, setNum] = useState(0);

  const handleScroll = () => {
    const scrollTop = document.getElementById(scrollContainerId)?.scrollTop;
    const clientHeight = document.getElementById(scrollContainerId)?.clientHeight;
    const scrollHeight = document.getElementById(scrollContainerId)?.scrollHeight;

    if (scrollTop + clientHeight + 50 > scrollHeight) {
      setNum(num + 1);
      
      // Replace this condition with your own logic to determine when to stop loading more data
      if (num >= 3) {
        setIsLoadComplete(true);
        return;
      }
      
      fetchDataCallback();
    }
  };

  useEffect(() => {
    const scrollElement = document.getElementById(scrollContainerId);
    scrollElement.addEventListener('scroll', handleScroll);

    return () => {
      scrollElement.removeEventListener('scroll', handleScroll);
    };
  }, [scrollContainerId]);

  return isLoadComplete;
};

export default useInfiniteScroll;

使用时,首先导入该自定义 Hook:

import useInfiniteScroll from './useInfiniteScroll';

然后,在组件中调用 useInfiniteScroll 并传递相应的参数和数据获取函数:

const MyComponent = () => {
  const fetchDataCallback = () => {
    // Simulate fetching more data here and update state accordingly
    // Example:
    let newStateData = [
      {
        historyUrl: $tools.IMG_RIGHT_ARROW,
        textDay: '嘻嘻嘻嘻',
        cumSgin: '下踩踩踩踩踩踩',
        Integral: 1,
        activeValue: 2,
        mallVoucher: 3,
      },
      {
        historyUrl: $tools.IMG_RIGHT_ARROW,
        textDay: '嘻嘻嘻嘻',
        cumSgin: '下踩踩踩踩踩踩',
        Integral: 1,
        activeValue: 2,
        mallVoucher: 3,
      },
    ];

    setHistoryData((data) => [...data, ...newStateData]);
  };

  const isLoadComplete = useInfiniteScroll('history-scroll', fetchDataCallback);

  // Render your component and handle the loading complete state (isLoadComplete)
};

在上述示例中,useInfiniteScroll 自定义 Hook 接受两个参数:滚动容器的 id 和一个回调函数 fetchDataCallback,用于获取更多数据。通过返回的 isLoadComplete 状态可以判断是否完成加载。这样就将之前的代码块封装为了一个可复用的方法,方便在其他组件中使用。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=9980

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?