可以将该代码块封装成一个公用的方法,以便在其他组件中复用。以下是将其封装为一个可调用的函数示例:
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助手提供,问题来源于学员提问