ReactNative之ListView分组样式(九)

前言

眼看很多公司都开始尝试使用ReactNative,达到跨平台开发,最近也写了很多文章,希望让更多想了解的同学快速上手ReactNative.

如果喜欢我的文章,可以关注我微博:袁峥Seemygo

ReactNative之ListView分组样式

  • 什么是ListView分组样式
城市列表.png
  • 要想明白ListView如何分组,得知道ListView底层是如何获取组数据,行数据

ListView分组原理

  • ListView默认支持3种数据格式,只要按照这3种格式处理数据,就会自动获取数据,从而达到分组样式
默认的提取函数可以处理下列形式的数据:

{ sectionID_1: { rowID_1: rowData1, ... }, ... }

或者:

{ sectionID_1: [ rowData1, rowData2, ... ], ... }

或者:

[ [ rowData1, rowData2, ... ], ... ]
3种提前格式.png

实现ListView分组样式步骤

  • 1.创建数据源,描述什么时候需要加载下一个cell和下一个section
// 1.创建数据源
        var dataSource = new ListView.DataSource({
            rowHasChanged:(r1,r2)=>r1 !== r2,
            sectionHeaderHasChanged:(s1,s2)=>s1 !== s2
        });

  • 2.处理数据,让数据跟默认提前的格式一样
var sectionData = {};
        for (var i = 0;i < provinceList.length;i++){
            var province = provinceList[i];
            var cityList = province['sub'];

            var cityArr = [];
            for(var cityIndex = 0;cityIndex < cityList.length;cityIndex++) {
                var city = cityList[cityIndex];
                cityArr.push(city['name']);
            }
            sectionData[province['name']] = cityArr;
        }

  • 3.设置数据
    • 分组使用:cloneWithRowsAndSections
    • 不分组使用:cloneWithRows
this.state = {
            ds : dataSource.cloneWithRowsAndSections(sectionData)
        }
  • 4.渲染listView
 render() {
        return (

            <View style={{flex:1,marginTop:20}}>
                <ListView dataSource={this.state.ds}
                          renderRow={this._renderRow.bind(this)}
                          renderSectionHeader={this._renderSectionHeader.bind(this)}
                          renderSeparator={this._renderSeparator.bind(this)}
                />
            </View>
        )

    }
    _renderSeparator() {
        return (
            <View style={{height:1,backgroundColor:'#e8e8e8'}}/>
        )
    }

    _renderSectionHeader(sectionData, sectionID) {
        return (
            <View style={{backgroundColor:'rgb(247,247,247)'}}>
                <Text style={styles.sectionStyle}>{sectionID}</Text>
            </View>
        )
    }

    // 实现数据源方法,每行cell外观
    _renderRow(rowData, sectionID, rowID, highlightRow) {
        return (
            <View style={{backgroundColor:'white',height:45,justifyContent:'center'}}>
                <Text style={styles.rowStyle}>{rowData}</Text>
            </View>
        );
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容