ReactNative基础(八)了解FlatList的使用、添加头尾布局、下拉
发布时间:2020-12-15 06:43:39 所属栏目:百科 来源:网络整理
导读:此博客基于react-native-0.49.3 之前我们已经说过ListView这个控件了、FlatList性质也是一样的只不过使用起来更加封闭、内部封装好了 添加头尾布局、下拉刷新、上拉加载等功能… 实现的效果: FlatList实现一个最简单的列表 FlatList //数据源 data={[{key:
此博客基于react-native-0.49.3之前我们已经说过ListView这个控件了、FlatList性质也是一样的只不过使用起来更加封闭、内部封装好了 添加头尾布局、下拉刷新、上拉加载等功能…实现的效果:FlatList实现一个最简单的列表<FlatList
//数据源
data={[{key: 'a'},{key: 'b'}]}
//渲染每一个Item
renderItem={({item}) => <Text>{item.key}</Text>}
/>
来实现一个见的最多的列表,从网络获取数据、解析并展示出来。
static defaultProps = { url: 'https://news-at.zhihu.com/api/4/news/latest' };
constructor(props) { super(props); this.state = { data: [],//存储列表使用的数据 refreshing: false,//当前的刷新状态 };
}
render() {
return (
<View style={styles.container}>
<FlatList data={this.state.data} keyExtractor={this.keyExtractor} renderItem={this.getView} //添加头尾布局 ListHeaderComponent={this.header} ListFooterComponent={this.footer} //下拉刷新,必须设置refreshing状态 onRefresh={this.onRefresh} refreshing={this.state.refreshing} />
</View>
);
}
添加头尾布局使用ListHeaderComponent、ListFooterComponent 数据即可,关于FlatList组件更多的属性和方法可以参考官方文档//头尾布局都是一样,这里就只贴出一个头布局以供参考 header = () => { return ( <Text style={{ backgroundColor: '#4398ff',color: 'white',fontSize: 18,textAlign: 'center',textAlignVertical: 'center',height: 150,}}>我是头布局</Text> ) };
请求网络数据加载列表数据//渲染完成,请求网络数据
componentDidMount() {
fetch(this.props.url)
.then((response) => response.json()) .then((response) => { //解析json数据 var json = response['stories']; //更新状态机 this.setState({ data: json,}); }) .catch((error) => { if (error) { //网络错误处理 console.log('error',error); } }); }
接下来就是对列表进行刷新操作。
/** * 下拉属性 */
onRefresh = () => {
//设置刷新状态为正在刷新
this.setState({
refreshing: true,});
//延时加载
const timer = setTimeout(() => {
clearTimeout(timer);
//往数组的第一位插入数据,模拟数据新增,unshift()会返回数组的长度
this.state.data.unshift(new this.ItemData('https://pic2.zhimg.com/v2-8f11b41f995ca5340510c1def1c003d1.jpg','下拉刷新添加的数据——————' + this.count,475843));
this.count++;
this.setState({
refreshing: false,});
},1500);
};
/** * json 数据实体类 */
ItemData(images,title,id) {
this.images = new Array(images);
this.title = title;
this.id = id;
}
上拉加载:我这里配置下面两个属性的时候一直出不来效果不知道为什么,有会的大佬欢迎留言或者贴个源码地址,在此感谢大家了。onEndReachedThreshold={0}
onEndReached={this.onEndReached}
源码下载地址推荐阅读:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |