React Native学习(10)长列表
FlatList
FlatList更适于长列表数据,且元素个数可以增删。和ScrollView不同的是,FlatList并不立即渲染所有元素,而是优先渲染屏幕上可见的元素。
FlatList组件必须的两个属性是data和renderItem。data是列表的数据源,而renderItem则从数据源中逐个解析数据。
如:
/**
* 慢慢学习
* https://blog.csdn.net/quanhaoH
*/
import React, { Component } from 'react';
import { AppRegistry, FlatList, StyleSheet, Text, View } from 'react-native';
export default class MyApp extends Component {
render() {
return (
<View style={styles.container}>
<FlatList
//创建假数据
data={[
{key: '1'},
{key: '2'},
{key: '3'},
{key: '4'},
{key: '5'},
{key: '6'},
{key: '7'},
{key: '8'},
]}
//数据解析
renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 22,
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
})
AppRegistry.registerComponent('MyApp', () => MyApp);
SectionList
如果要渲染的是一组需要分组的数据,也许还带有分组标签的,SectionList会比较好。
如:
/**
* 慢慢学习
* https://blog.csdn.net/quanhaoH
*/
import React, { Component } from 'react';
import { AppRegistry, SectionList, StyleSheet, Text, View } from 'react-native';
export default class MyApp extends Component {
render() {
return (
<View style={styles.container}>
<SectionList
sections={[
{title: '第一组', data: ['1']},
{title: '第二组', data: ['1', '2', '3', '4', '5', '6', '7']},
]}
renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
keyExtractor={(item, index) => index}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 22
},
sectionHeader: {
paddingTop: 2,
paddingLeft: 10,
paddingRight: 10,
paddingBottom: 2,
fontSize: 14,
fontWeight: 'bold',
backgroundColor: 'rgba(247,247,247,1.0)',
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
})
AppRegistry.registerComponent('MyApp', () => MyApp);