// rnc
// FlatList: 高性能的列表组件
import React, {Component} from 'react';
import {
ActivityIndicator,
Dimensions,
FlatList,
Image,
Text,
TouchableOpacity,
View,
} from 'react-native';
const {width, height} = Dimensions.get('screen');
const rpx = (x) => (width / 750) * x;
export default class Douyu extends Component {
url = 'http://capi.douyucdn.cn/api/v1/live?limit=20&offset=';
// refreshing: 控制刷新动画的 显示与否
state = {data: [], refreshing: false};
componentDidMount() {
fetch(this.url + 0)
.then((res) => res.json())
.then((res) => {
console.log(res);
this.setState({data: res.data});
});
}
render() {
/**
* 3 个核心属性:
* 1. data: 数据项
* 2. renderItem: 每一项数据 对应的UI
* 3. keyExtractor: 每一个UI 对应的唯一标识
*/
return (
<FlatList
data={this.state.data}
keyExtractor={(item, index) => index + ''}
renderItem={this._renderItem}
ItemSeparatorComponent={() => (
<View style={{height: 1, backgroundColor: 'gray'}} />
)}
ListFooterComponent={this._ListFooterComponent}
onEndReachedThreshold={0.1}
onEndReached={this._onEndReached}
refreshing={this.state.refreshing}
onRefresh={this._onRefresh}
/>
);
}
_onRefresh = () => {
this.setState({refreshing: true});
fetch(this.url + 0)
.then((res) => res.json())
.then((res) => {
console.log(res);
// 更新数据 并 结束刷新动画
this.setState({data: res.data, refreshing: false});
});
};
_onEndReached = () => {
// 分页参数: 已有数据数量. 服务器会根据此参数 返回接下来的数据
// 不同服务器的分页设计会不同, 具体要看接口要求
fetch(this.url + this.state.data.length)
.then((res) => res.json())
.then((res) => {
console.log(res);
// 合并 新旧数据
this.state.data = this.state.data.concat(res.data);
this.setState({}); //更新UI
});
};
_ListFooterComponent = () => (
<View style={{alignItems: 'center'}}>
<ActivityIndicator size="large" color="orange" />
<Text style={{fontSize: rpx(30)}}>加载中...</Text>
</View>
);
// 语法糖: 解包参数
_renderItem = ({item, index}) => {
// 箭头函数语法糖适合简单的返回, 此处要进行较为复杂的操作, 不适合写语法糖
// console.log(item.room_src);
// 热度过万
let hn = item.hn;
if (hn >= 10000) {
// toFixed(1): 保留1位小数
hn = (hn / 10000).toFixed(1) + '万';
}
return (
<TouchableOpacity
onPress={() =>
this.props.navigation.push('Live', {room_id: item.room_id})
}
style={{flexDirection: 'row', padding: 4}}>
<Image
source={{uri: item.room_src}}
style={{width: rpx(320), height: rpx(180)}}
/>
<View style={{justifyContent: 'space-between', flex: 1, marginLeft: 4}}>
<Text style={{fontSize: rpx(30)}}>{item.room_name}</Text>
<Text style={{fontSize: rpx(30)}}>{item.nickname}</Text>
<Text style={{fontSize: rpx(30)}}>{hn}</Text>
</View>
</TouchableOpacity>
);
};
}
【RN-尺寸兼容rpx】
最新推荐文章于 2024-09-09 09:35:48 发布
本文展示了如何在ReactNative应用中使用FlatList组件来创建高性能的列表。通过fetch获取数据,设置数据源、渲染单项、处理分页和刷新功能,同时用到的其他组件包括ActivityIndicator和TouchableOpacity等。
摘要由CSDN通过智能技术生成