1、虚拟列表 核心原理就是 比如有100条数据 如果全部渲染出来,那么dom结构里面对应有100个对应的dom,比如1000 10000的时候,就会开始影响页面性能,那么就要实现虚拟列表, dom结构里面永远只渲染10条 或者 页面可展示的条数,那么性能就会大大提升!
2、实现原理
function Home(props: Props) {
let lessonListRef = useRef(null);
useEffect(()=>{
lessonListRef.current();
//重新渲染组件
homeContainerRef.current.addEventListener('scroll',throttle(lessonListRef.current,16));
},[]);//依赖数组为空表示此effect回调只会执行一次
return (
<>
<div className="home-container" ref={
homeContainerRef}>
<LessonList
lessons={
props.lessons}
getLessons={
props.getLessons}
ref={
lessonListRef}
homeContainerRef={
homeContainerRef}
/>
</div>
</>
)
}
-
2.1 先定义ref : lessonListRef传入给LessonList组件,外层容器homeContainerRef绑定scroll事件,那么容器滚动的时候,就会执行lessonListRef.current方法。
-
2.2
let [,forceUpdate] = React.useReducer(x=>x+1,0);
只是为了定义一个强制刷新的函数forceUpdate 然后赋值给forwardedRef.current = forceUpdate; -
2.3 remSize 就是1rem代表多少px 比如37.5
-
2.4 itemSize 就是计算当前每个item高度是多少px 比如原来是650px的设计图高度 650 /75就是rem rem*remSize就是实际高度
-
2.5 screenHeight 显示内容的高度
-
2.6 scrollTop 父容器滚动的距离
-
2.7 start = Math.floor(scrollTop/itemSize); start索引就是展示的起始索引 因为卷去的高度/item高度 就是代表滚到第几个
-
2.8 end = start + Math.floor(screenHeight/itemSize); screenHeight/itemSize就是屏幕最多展示的个数 开始+展示个数 就是end
<