RN 列表组件之二 SectionList
#
sections的数据源格式
1、不同section渲染相同类型的子组件
[
{data: […], key: …},
{data: […], key: …},
{data: […], key: …}
]
2、 不同section渲染不同类型的子组件
[
{data: […], key: …, renderItem: …},
{data: […], key: …, renderItem: …},
{data: […], key: …, renderItem: …},
]
componentDidMount() {
this.getHomepageData()
}
<SectionList
ref='sectionList' // this.refs.sectionList 获取组件本身
sections={this.state.sectionData} //渲染的数据源
ListEmptyComponent={this.emptyView.bind(this)} //组件为空时
ListHeaderComponent={this._listHeaderComponent.bind(this)} //头部渲染
ListFooterComponent={this._listFooterComponent.bind(this)} //底部渲染
renderSectionHeader={this._sectionComp.bind(this)} // 列表头部渲染
renderItem={this._sectionRenderItem.bind(this)} //列表渲染
stickySectionHeadersEnabled={true} // 滚动粘粘在顶部
keyExtractor={this._keyExtractor.bind(this)} //唯一key值
refreshing={this.state.isRefreshing} //是否下拉刷新
onRefresh={this._onRefresh.bind(this)} //下拉刷新
onEndReached={this._endReached.bind(this)} //上拉刷新
onEndReachedThreshold={0.1} //当列表被滚动到距离内容最底部不足0.1的距离时调用
/>
getHomepageData(){
//第一次页面网络获取数据源
}
_endReached(){
let that=this
//排除 首次为满一屏会触发的情况
if(that.state.sectionData[0].data && that.state.sectionData[0].data.length < parseInt(that.state.totalCount)){
that.state.currentPage++;
that.getMoreList();
}else{
//若总数未满一屏,进去就提示
alert('已加载完所有数据')
}
}
getMoreList(){
//网络请求获取新数据源
}
_onRefresh() {
let that=this
that.componentDidMount()
}
_keyExtractor(info, index) {
return index;
}
_sectionRenderItem(){
return(
<TouchableOpacity key={index} >
<View style={{justifyContent: 'center', alignItems: 'center'}}>
<Image source = {require('../images/1.png')} />
<View style={{position:'absolute',flex:1,bottom:0,left:0,right:0,paddingTop:5,paddingBottom:5,justifyContent:'center',paddingLeft:10,backgroundColor:'rgba(50,50,50,0.7)'}}>
<Text style={{fontSize: yfont(15),lineHeight: yheight(17), color: '#fff' }} numberOfLines={2} ellipsizeMode= 'tail'>{item.title}</Text>
</View>
</TouchableOpacity>
)
}
_sectionComp(){
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>
)
}
_listHeaderComponent(){
return(
<View style={{flex:1}}>
<Text>头部布局</Text>
</View>
)
}
emptyView(){
return(
<View style={{flex: 1}}>
<Text>暂无数据</Text>
</View>
)
}