页面滑动到底部,直接加载下一页数据
- InfiniteScroll.tsx
/*** 无限 加载组件*/import { FC, createRef, useEffect, CSSProperties } from 'react'
import LoadingText from '../LoadingText'type PropsType = {loadMore: () => voidhasMore: boolean
}const InfiniteScroll: FC<PropsType> = (props: PropsType) => {const { loadMore, hasMore } = props// const [loading, setLoading] = useState(hasMore)const ref = createRef<HTMLDivElement>()// console.log('InfiniteScroll', hasMore)useEffect(() => {const observer = new IntersectionObserver((entries, observer) => {entries.forEach((entry) => {if (entry.isIntersecting) {// setLoading(false)loadMore()}})})// console.log('ref.current', ref.current)if (ref.current) {observer.observe(ref.current)}}, [])const defaultStyle: CSSProperties = {padding: '0 0 0.6rem 0'}return (<div className="scroll-load-more" ref={ref}>{hasMore ? (<LoadingText defaultStyle={defaultStyle} />) : (<LoadingText><divstyle={{...defaultStyle,textAlign: 'center',fontSize: '0.28rem',color: '#999'}}>--- 我是有底线的 ---</div></LoadingText>)}</div>)
}export default InfiniteScroll
- 用法
....
<InfiniteScroll loadMore={loadMore} hasMore={hasMore} />async function loadMore() {// 加载下一页数据}// hasMore 是 判断是否还有数据状态