react实现微博滑动
实现微博滑动效果的核心思路
微博滑动效果通常指下拉刷新和上拉加载更多功能。React中可以通过监听滚动事件或使用现成库实现。
使用自定义滚动监听实现
监听滚动位置计算是否到达容器底部或顶部触发对应操作:
import { useState, useEffect, useRef } from 'react';
function WeiboList() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const containerRef = useRef(null);
useEffect(() => {
fetchData();
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
const fetchData = () => {
setLoading(true);
// 模拟API请求
setTimeout(() => {
setData(prev => [...prev, ...new Array(10).fill(0).map((_,i) =>
`微博内容 ${prev.length + i + 1}`
)]);
setLoading(false);
}, 1000);
};
const handleScroll = () => {
if (loading) return;
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
// 到达底部加载更多
if (scrollTop + clientHeight >= scrollHeight - 100) {
fetchData();
}
};
return (
<div ref={containerRef}>
{data.map((item, i) => (
<div key={i} style={{padding: '20px', borderBottom: '1px solid #eee'}}>
{item}
</div>
))}
{loading && <div>加载中...</div>}
</div>
);
}
使用react-infinite-scroll-component库
更简单的实现方式是使用专门处理无限滚动的React库:
import InfiniteScroll from 'react-infinite-scroll-component';
function WeiboList() {
const [data, setData] = useState([]);
const [hasMore, setHasMore] = useState(true);
const fetchData = () => {
// 模拟API请求
setTimeout(() => {
setData(prev => [...prev, ...new Array(10).fill(0).map((_,i) =>
`微博内容 ${prev.length + i + 1}`
)]);
// 模拟数据加载完毕
if (data.length >= 50) setHasMore(false);
}, 1000);
};
return (
<InfiniteScroll
dataLength={data.length}
next={fetchData}
hasMore={hasMore}
loader={<h4>加载中...</h4>}
endMessage={<p>没有更多内容了</p>}
>
{data.map((item, i) => (
<div key={i} style={{padding: '20px', borderBottom: '1px solid #eee'}}>
{item}
</div>
))}
</InfiniteScroll>
);
}
添加下拉刷新功能
实现下拉刷新需要监听touch或鼠标事件:
const [refreshing, setRefreshing] = useState(false);
const handleRefresh = () => {
setRefreshing(true);
setTimeout(() => {
setData(new Array(10).fill(0).map((_,i) => `最新微博 ${i+1}`));
setRefreshing(false);
}, 1000);
};
// 在渲染中添加下拉刷新UI
{refreshing && (
<div style={{textAlign: 'center', padding: '10px'}}>
正在刷新...
</div>
)}
性能优化建议
对于长列表渲染应使用虚拟滚动技术,推荐使用react-window库:
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>
微博内容 {data[index]}
</div>
);
<List
height={600}
itemCount={data.length}
itemSize={80}
width="100%"
>
{Row}
</List>






