无限滚动组件

借助IntersectionObserver实现LoadMore组件,无限下拉加载数据。边界控制没有处理

LoadMore.tsx:

import React, { useEffect, useRef } from "react";
import "./index.css";
/**
.load-more {
  height: 100px;
  background: #eee;
  text-align: center;
  line-height: 100px;
}

**/

function LoadMore(props) {
  const ref = useRef();
  const loadMoreRef = useRef(()=>{});
  loadMoreRef.current = props.loadMore;//持久化函数
  
  useEffect(() => {
    console.log("loadMore");
    const observer = new IntersectionObserver(entries => {
      if (entries[0].intersectionRatio <= 0) return;
      console.log(entries);
      loadMoreRef.current && loadMoreRef.current();
    });
    observer.observe(ref.current);
    return () => {
      observer.disconnect();
    };
  }, []);

  return (
    <div className="load-more" ref={ref}>
      加载更多
    </div>
  );
}

export default LoadMore;

App.tsx

import React, { useState, useCallback } from "react";
import ReactDOM from "react-dom";
import LoadMore from "./LoadMore";
import "./index.css";
/**
.card {
  margin: 20px;
  border: 1px solid #ddd;
  border-radius: 6px;
  height: 60px;
  line-height: 60px;
}
**/

const App: React.FC = () => {
  const [list, setList] = useState(() => {
    return new Array(20).fill(0); //只会执行一次初始化数据
  });
  return (
    <div>
      {list.map((item, index) => (
        <div className="card" key={index}>
          {item}
        </div>
      ))}
      <LoadMore
        loadMore={() => {
          console.log("加载更多");
          setTimeout(() => {
            const newList = new Array(20).fill(Math.random());
            setList([...list, ...newList]);
          }, 1000);
        }}
      />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青菜小王子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值