里面的tw是在react native中使用tailwind的第三方库
只求读者把样式看个大概,主要还是功能的实现
ScrollView的官方文档如下
https://reactnative.cn/docs/scrollview
import tw from 'twrnc'
import { View, Text, ScrollView, RefreshControl } from 'react-native'
import { useState, useEffect } from 'react'
const MyScrollView = ({ }) => {
const [data, setData] = useState([]);
const [refreshing, setRefreshing] = useState(false);
const handleTopRefresh = () => {
// 防抖
if (refreshing === false) {
setRefreshing(true);
console.log("触发上拉刷新")
setTimeout(() => {
console.log("拿到新数据")
setRefreshing(false);
}, 1500);
}
};
const handleBottomRefresh = (e) => {
// 防抖
if (refreshing === false) {
const offsetY = e.nativeEvent.contentOffset.y; //滑动距离
const contentSizeHeight = e.nativeEvent.contentSize.height; //scrollView contentSize高度
const scrollHeight = e.nativeEvent.layoutMeasurement.height; //scrollView高度
//似乎有时会有误差,比如滑到底部但是(755.9999771118164<756),我的解决思路是取ceil
if (Math.ceil(offsetY + scrollHeight) >= contentSizeHeight) {
console.log("触发底部刷新")
setRefreshing(true);
setTimeout(() => {
console.log("拿到新数据")
setRefreshing(false);
}, 1500);
}
}
}
useEffect(() => {
const res = [];
for (let i = 0; i < 19; i++) {
res.push(i);
}
setData(res);
}, [])
return (
<ScrollView
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={handleTopRefresh} />
}
onMomentumScrollEnd={handleBottomRefresh}
style={tw`flex-1`}>
<View style={tw`gap-1 `}>
{data.map((item, idx) => (
<Text style={tw`text-center text-3xl bg-yellow-200`} key={idx}>{item}</Text>
))
}
</View>
</ScrollView>
)
}
export default MyScrollView;
演示动画注意看终端里的输出
顺便看到了一个Toast组件,直接拿来当做加载后的提示了
https://github.com/calintamas/react-native-toast-message/tree/main
秉持着不水短文章的做法,附加上我自己写的白屏加载组件
Modal应该是absolute的组件,所以这个组件放哪都行
这里我查资料的时候才知道官方有写好了加载动画组件
import tw from 'twrnc'
import { View, Modal, ActivityIndicator } from 'react-native'
const Loading = ({ visible = false }) => {
return (
<Modal visible={visible} transparent={true}>
<View style={tw`bg-white opacity-80 h-full w-full items-center justify-center`}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
</Modal>
)
}
export default Loading;