React Native填坑之旅--ListView的Section Header
React Native自己实现的ListView还有一个隐藏功能那就是Section。Section在文档里连一句话都没有给足,但确确实实的是内置的。使用Section可以给数据分组,并且每一个Section都有一个Header。Section Header可以像iOS的TableView的Section Header一样在滑动的时候保持当前的Section Header浮动在Table View的最上部。 在iOS上,只要添加了Section和Section Header以后,Section Header的行为就一定是和iOS的TableView的Section Header 一致的。这个在Android上还没有测试。 数据源的变化要使用Section,那么首先一开始就需要告诉数据源不仅要考虑行的变化还要考虑Section Header的变化: const ds = new ListView.DataSource({ rowHasChanged: (r1,r2) => r1 !== r2,sectionHeaderHasChanged: (s1,s2) => s1 !== s2 }); 然后就要考虑数据的变化了。之前只需要一个数组就可以完成的,现在需要数据可以明确的区分出Section。最简单的一个数据源应该是这样的: this.state = { dataSource: ds.cloneWithRowsAndSections({ 'section1': ['1'],'section2': ['row 1','row 2','row 1','row 2'] }) }; 单独的看数据是这样的一个形式: { 'section1': ['1'],'row 2'] } 绘制的变化在没有Section的时候,绘制很简单。只需要实现一个 _renderSectionHeader(data,sectionID) { if (sectionID === 'section1') { return null } return ( <View style={styles.section}> <View style={{flex: 1}}><Text>category 1</Text></View> <View style={{flex: 1}}><Text>category 2</Text></View> <View style={{flex: 1}}><Text>category 3</Text></View> </View> ); } 拼接起来以上的内容就是使用一个Section方法都需要的只是了。非常简单,但是官网居然不把这些内容放出来。 下面贴出了ListView 部分的代码,完整代码可以移步这里。 /* * Copy Right 2016 Uncle Charlie * * @flow */ import React,{ Component } from 'react'; import { View,Text,ListView,StyleSheet } from 'react-native'; export default class SectionListView extends Component { state: {dataSource: any}; constructor(props: any) { super(props); const ds = new ListView.DataSource({ rowHasChanged: (r1,s2) => s1 !== s2 }); this.state = { dataSource: ds.cloneWithRowsAndSections({ 'section1': ['1'],'row 2'] }) }; this._renderRow = this._renderRow.bind(this); this._renderSectionHeader = this._renderSectionHeader.bind(this); } _renderRow(data,sectionID,rowID) { let heightStyle = (sectionID === 'section1' && rowID === '0') ? {height: 100,backgroundColor: 'white'} : {} return ( <View style={[styles.row,heightStyle]}> <Text>{data}</Text> </View> ); } _renderSectionHeader(data,sectionID) { if (sectionID === 'section1') { return null } return ( <View style={styles.section}> <View style={{flex: 1}}><Text>category 1</Text></View> <View style={{flex: 1}}><Text>category 2</Text></View> <View style={{flex: 1}}><Text>category 3</Text></View> </View> ); } render() { return ( <ListView style={styles.list} dataSource={this.state.dataSource} renderRow={this._renderRow} renderSectionHeader={this._renderSectionHeader} /> ); } } var styles = StyleSheet.create({ list: { marginTop: 64,},row: { height: 50,backgroundColor: 'white' },section: { height: 30,backgroundColor: 'green',flexDirection: 'row',justifyContent: 'space-between',alignItems: 'center' } }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |