react-native中FlatList的使用

原文地址:https://medium.com/react-native-development/how-to-use-the-flatlist-component-react-native-basics-92c482816fe6

简介

自从0.43版本以来,react-native新增了两个新的列表视图组件:FlatList以及SectionList,现在我们来看看FlatList组件的使用。

简单示例

FlatList中有个比较重要的属性:datarenderItem属性,data为object数组,renderItem可以控制每个item的渲染规则。

这边的示例我们将会从Random User Generator API中拿,UI渲染将会使用react-native-elements的组件。

点击查看完整源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//FlatListDemo.js
import React, { Component } from "react";
import { View, Text, FlatList } from "react-native";
class FlatListDemo extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
page: 1,
seed: 1,
error: null,
refreshing: false,
};
}
componentDidMount() {
this.makeRemoteRequest();
}
makeRemoteRequest = () => {
const { page, seed } = this.state;
const url = `https://randomuser.me/api/?seed=${seed}&page=${page}&results=20`;
this.setState({ loading: true });
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
data: page === 1 ? res.results : [...this.state.data, ...res.results],
error: res.error || null,
loading: false,
refreshing: false
});
})
.catch(error => {
this.setState({ error, loading: false });
});
};
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>Coming soon...</Text>
</View>
);
}
}
export default FlatListDemo;

然后外边就可以使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import FlatList from './FlatListDemo.js';
import React from 'react';
import { List, ListItem } from 'react-native-elements';
class AwesomeProject extends React.Component{
render(){
<List>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<ListItem
roundAvatar
title={`${item.name.first} ${item.name.last}`}
subtitle={item.email}
avatar={{ uri: item.picture.thumbnail }}
keyExtractor={item => item.email}
/>
)}
/>
</List>
}
}

效果图如下:

demo