React Native SectionList组件是一个列表视图组件,该组件将数据列表设置为破碎的逻辑部分。使用prop renderSectionHeader来实现。
要实现SectionList组件,我们需要从“ react-native”库中导入SectionList。
sections | renderItem | initialNumToRender | keyExtractor |
renderSectionHeader | renderSectionFooter | onRefresh | inverted |
extraData | onEndReached | keyExtractor | legacyImplementation |
onViewableItemsChanged | refreshing | removeClippedSubviews | ListHeaderComponent |
SectionSeparatorComponent | stickySectionHeadersEnabled | onEndReachedThreshold | ListEmptyComponent |
在此示例中,我们创建一个带有标题和数据的SectionList。 props部分用于创建标题(title)和数据值(data values)的列表。 renderSectionHeader显示list view的标题部分。
import React, { Component } from 'react'; import { AppRegistry, SectionList, StyleSheet, Text, View } from 'react-native'; export default class SectionListBasics extends Component { render() { return ( <View style={styles.container}> <SectionList sections={[ {title: 'A', data: ['ALTERED','ABBY','ACTION U.S.A.','AMUCK','ANGUISH']}, {title: 'B', data: ['BEST MEN','BEYOND JUSTICE','BLACK GUNN','BLOOD RANCH','BEASTIES']}, {title: 'C', data: ['CARTEL', 'CASTLE OF EVIL', 'CHANCE', 'COP GAME', 'CROSS FIRE',]}, ]} 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, backgroundColor: "#5ead97" }, sectionHeader: { paddingTop: 2, paddingLeft: 10, paddingRight: 10, paddingBottom: 2, fontSize: 22, fontWeight: 'bold', color: "#fff", backgroundColor: '#8fb1aa', }, item: { padding: 10, fontSize: 18, height: 44, } }) // 如果使用 Create React Native App,请跳过此行 AppRegistry.registerComponent('AwesomeProject', () => SectionListBasics);
输出:
ItemSeparatorComponent属性在数据列表之间添加分隔符。使用此道具,调用renderSeparator方法,在其中添加一个View组件作为分隔符。
renderSeparator = () => { return ( <View style={{ height: 1, width: "100%", backgroundColor: "#000", }} /> ); }; ItemSeparatorComponent={this.renderSeparator}
要执行单击(按下)列表项的操作,我们使用onPress prop属性。 onPress属性并使用另一个方法getListViewItem处理该事件。
//处理 onPress 动作 getListViewItem = (item) => { alert(item); } renderItem={({item}) => <Text style={styles.item} onPress={this.getListViewItem.bind(this, item)}>{item}</Text>}
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)