listView需要兩個(gè)關(guān)鍵數(shù)據(jù)婚夫,一個(gè)是row或者section的更新策略家凯;一個(gè)是需要顯示的data數(shù)據(jù)缓醋。
這里使用rowHasChanged和sectionHeaderHasChanged更新策略,也是最常見的策略绊诲。
1:在構(gòu)造函數(shù)中創(chuàng)建更新策略和數(shù)據(jù)
constructor(props) {
super(props);
let ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 != r2,
sectionHeaderHasChanged: (s1, s2) => s1 != s2,
});
this.state = {
datasource: ds,
data: {'a': ['aaa', 'bbb', 'ccc', 'ddd'], 'b': ['eee', 'fff', 'www', 'rrr']},
}
}
2:在創(chuàng)建listView的時(shí)候使用更新策略和數(shù)據(jù)源數(shù)據(jù)
//創(chuàng)建listview界面
//dataSource定義了策略和數(shù)據(jù)
//renderRow定義行顯示的view
contantView = () => {
return(
<ListView style={styles.listViewStyle}
dataSource={this.state.datasource.cloneWithRowsAndSections(this.state.data)}
renderRow={(rowData, sectionId, rowId) => this.decideRowSectionView(rowData, sectionId, rowId)}
/>
)
};
3:以下為renderRow顯示的view
//判斷顯示row和section
decideRowSectionView = (rowData, sectionId, rowId) => {
if (upSectionId != sectionId) {
upSectionId = sectionId;
return(
this.sectionView(rowData, sectionId, rowId)
)
}else {
return(
this.rowView(rowData, sectionId, rowId)
)
}
};
//創(chuàng)建row顯示的view
rowView = (rowData, sectionId, rowId) => {
return(
<View style={styles.rowViewStyle}>
<Image style={styles.rowViewImageStyle}
source={{uri: '/Users/kk/SampleAppMovies/image/a11.jpg'}}
/>
<Text style={styles.rowViewTextStyle}>
{'當(dāng)前數(shù)據(jù)' + rowData + ' sectionId ' + sectionId + ' rowId ' + rowId}
</Text>
</View>
)
};
//創(chuàng)建section顯示的view
//不能使用float屬性送粱,這里用了ScrollView來限定Text的顯示
sectionView = (rowData, sectionId, rowId) => {
return(
<View style={styles.sectionViewStyle}>
<View style={styles.sectionUpViewStyle}>
<Image style={styles.rowViewImageStyle}
source={{uri: '/Users/kk/SampleAppMovies/image/c11.jpg'}}
/>
<ScrollView style={styles.sectionScrollViewStyle}>
{<Text>千里鶯啼綠映紅,水村山郭酒旗風(fēng)掂之。南朝四百八十寺抗俄,多少樓臺煙雨中。</Text>}
</ScrollView>
</View>
<Text style={styles.rowViewTextStyle}>
鳳凰臺上鳳凰游世舰,鳳去臺空江自流动雹。吳宮花草埋幽徑,晉代衣冠成古丘跟压。三山半落青天外胰蝠,二水中分白鷺洲。總為浮云能蔽日茸塞,長安不見使人愁躲庄。
人生若只如初見,何事秋風(fēng)悲畫屏钾虐。等閑變卻故人心噪窘,卻道故人心易變。驪山雨露清宵半效扫,淚雨零鈴終不怨倔监。何如薄幸錦衣郎,比翼連枝當(dāng)日愿荡短。
</Text>
{this.rowView(rowData, sectionId, rowId)}
</View>
)
};
4:使用的style
const styles = StyleSheet.create({
rowViewStyle: {
flex: 1,
backgroundColor: '#1faadd',
flexDirection: 'row',
alignItems: 'center',
padding: 10,
borderBottomWidth: 0.5,
borderBottomColor: '#000000',
},
rowViewImageStyle: {
width: 40,
height: 44,
},
rowViewTextStyle: {
fontSize: 14,
marginLeft: 10,
},
sectionViewStyle: {
flex: 1,
backgroundColor: '#afaadd',
},
sectionUpViewStyle: {
flex: 1,
padding: 10,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#6f5afd',
borderBottomWidth: 0.1,
borderBottomColor: '#a01010',
},
sectionScrollViewStyle: {
margin: 10,
},
listViewStyle: {
flex: 1,
marginTop: 20,
},
rendViewStyle: {
flex: 1,
}
});
最終效果:
57B99D17-8F41-4230-B59D-06A27607B90C.png