前言
眼看很多公司都開始嘗試使用ReactNative,達(dá)到跨平臺(tái)開發(fā),最近也寫了很多文章刀脏,希望讓更多想了解的同學(xué)快速上手ReactNative.
如果喜歡我的文章局荚,可以關(guān)注我微博:袁崢Seemygo
ReactNative之ListView分組樣式
- 什么是ListView分組樣式
城市列表.png
- 要想明白ListView如何分組,得知道ListView底層是如何獲取組數(shù)據(jù),行數(shù)據(jù)
ListView分組原理
- ListView默認(rèn)支持3種數(shù)據(jù)格式,只要按照這3種格式處理數(shù)據(jù)愈污,就會(huì)自動(dòng)獲取數(shù)據(jù),從而達(dá)到分組樣式
默認(rèn)的提取函數(shù)可以處理下列形式的數(shù)據(jù):
{ sectionID_1: { rowID_1: rowData1, ... }, ... }
或者:
{ sectionID_1: [ rowData1, rowData2, ... ], ... }
或者:
[ [ rowData1, rowData2, ... ], ... ]
3種提前格式.png
實(shí)現(xiàn)ListView分組樣式步驟
- 1.創(chuàng)建數(shù)據(jù)源,描述什么時(shí)候需要加載下一個(gè)cell和下一個(gè)section
// 1.創(chuàng)建數(shù)據(jù)源
var dataSource = new ListView.DataSource({
rowHasChanged:(r1,r2)=>r1 !== r2,
sectionHeaderHasChanged:(s1,s2)=>s1 !== s2
});
- 2.處理數(shù)據(jù)耀态,讓數(shù)據(jù)跟默認(rèn)提前的格式一樣
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.設(shè)置數(shù)據(jù)
- 分組使用: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>
)
}
// 實(shí)現(xiàn)數(shù)據(jù)源方法,每行cell外觀
_renderRow(rowData, sectionID, rowID, highlightRow) {
return (
<View style={{backgroundColor:'white',height:45,justifyContent:'center'}}>
<Text style={styles.rowStyle}>{rowData}</Text>
</View>
);
}