React-Native SectionList布局介绍

先敬上炫酷的效果图:


9102DA01-DF73-4141-8767-286C3EFD1F91.png

前面学习了FlatListhttp://www.jianshu.com/p/c464a2688663
但是FlatList并不支持section的分组功能。

这里介绍SectionList完美的实现了分组功能,和FlatList一样,性能更优

主要属性:

renderItem:渲染每一个item,很重要哦
sections:提供数据源,很重要哦
ListHeaderComponent:列表-表头,可以不用
ListFooterComponent:列表-表尾巴,可以不用
renderSectionHeader:每一个分组section,分组必须要哈
keyExtractor:每个renderItem的key,如果相同则不渲染这个renderItem,很重要,很重要,很重要,千万不要重复

创建一个SectionList

<SectionList
  renderItem={({item}) => <ListItem title={item.title} />}
  renderSectionHeader={({section}) => <H1 title={section.key} />}
  sections={[ // 不同section渲染相同类型的子组件
    {data: [...], key: ...},
    {data: [...], key: ...},
    {data: [...], key: ...},
  ]}
/>

<SectionList
  sections={[ // 不同section渲染不同类型的子组件
    {data: [...], key: ..., renderItem: ...},
    {data: [...], key: ..., renderItem: ...},
    {data: [...], key: ..., renderItem: ...},
  ]}
/>

引用其他作者的话:

sections 就是我们的数据源,每一个data 就是我们要用的item, renderItem就是你要显示的子控件哦。如果你每个组都复用一个子组件那就按照例一的结构, 如果你想要不同的组返回不同样式的子组件那就按照例二的结构返回不同的renderItem即可。这里提个醒, key一定要有, 不同的section 要设置不同的key才会渲染相应的section, 如果你key值都相同, 那可能会出现只显示一组数据的情况哦~

这里的解释,是摘抄别人的,他的简书链接,本文也是参考这里的http://www.jianshu.com/p/6302c4d48b97

以下分别介绍SectionList的属性赋值,如果不想看,可以拉到最后,查看完整代码
1.为ListHeaderComponent创建一个view,作为表头

_listHeaderComponent =()=> {
        return(
            <View style={{backgroundColor: '#aaaaff'}}>
                <Text>
                    我是listHeader
                </Text>
            </View>
        )
    };

2.为ListFooterComponent创建一个view,作为表尾巴

_listFooterComponent =()=> {
         return(
             <View style={{backgroundColor: '#aaaaff'}}>
                 <Text>
                     我是listFooter
                 </Text>
             </View>
         )
    };

3.为renderSectionHeader创建一个view,作为每个section

//参数需要{}修饰,告诉section是个对象
    _renderSectionHeader = ({section}) => {
        return(
            <View style={{flex: 1, height: 25, backgroundColor: '#11ffff', justifyContent: 'center'}}>
                <Text style={styles.sectionHeader}>{section.key}</Text>
            </View>
        )
    };

4.为renderItem创建一个view,作为每个item

//先创建一个Row对象,代表每个item界面
class Row extends Component {
    _rowClick =()=>{
        let rowNum = this.props.data.row;
        alert(rowNum);
    };
    render(){
        return(
            <TouchableOpacity style={styles.row} onPress={this._rowClick}>
                <View style={{flex:1, alignItems: 'center', justifyContent: 'center', backgroundColor: this._backColor()}}>
                    <Text>
                        {this.props.data.value}
                    </Text>
                </View>
            </TouchableOpacity>
        )
    }
//随机取色的方法
    _backColor =()=> {
        let r=Math.floor(Math.random()*256);
        let g=Math.floor(Math.random()*256);
        let b=Math.floor(Math.random()*256);
        let s = "rgb("+r+','+g+','+b+")";
        console.log('_backColor'+s);
        return s;//所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`替换
    }
}
//使用用Row对象来创建item
//参数需要{}修饰,告诉item是个对象,其实这里的item是个数组包含对象,使用map来遍历数组
    _renderItem =({item})=> {
        return (
        <View style={styles.list}>
            {
                item.map((val, i)=>{
                    return <Row key={i} data={val}/>
                })
            }
        </View>
        )
    };

4.设置keyExtractor的值,确保此值不重复

_extraUniqueKey =(item)=> {
        return "index"+item;
    };

5.为SectionList添加数据源sections
//rowData是一个包含对象的数组

sections={
                             this.state.rowData
                         }>

上面就是为了给SectionList的每个属性附上东东,接下来就是创建一个SectionList

直接上完整代码吧:
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    View,
    SectionList,
    Text,
    Dimensions,
    TouchableOpacity
} from 'react-native';

let windowsSize = {
    width: Dimensions.get('window').width,
    height: Dimensions.get("window").height
};
class Row extends Component {
    _rowClick =()=>{
        let rowNum = this.props.data.row;
        alert(rowNum);
    };
    render(){
        return(
            <TouchableOpacity style={styles.row} onPress={this._rowClick}>
                <View style={{flex:1, alignItems: 'center', justifyContent: 'center', backgroundColor: this._backColor()}}>
                    <Text>
                        {this.props.data.value}
                    </Text>
                </View>
            </TouchableOpacity>
        )
    }
    _backColor =()=> {
        let r=Math.floor(Math.random()*256);
        let g=Math.floor(Math.random()*256);
        let b=Math.floor(Math.random()*256);
        let s = "rgb("+r+','+g+','+b+")";
        console.log('_backColor'+s);
        return s;//所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`替换
    }
}
export default class SectionView extends React.PureComponent{
    constructor(props){
        super(props);
        let data1 =  Array.from(new Array(5)).map((val, i)=>({
            value: '数据1='+i,
            row: i,
        }));
        let data2 =  Array.from(new Array(8)).map((val, i)=>({
            value: '数据2='+i,
            row: i,
        }));
        let data3 =  Array.from(new Array(11)).map((val, i)=>({
            value: '数据3='+i,
            row: i,
        }));
        //这里面的data属性后面跟数组,是为了在布局renderItem的时候可以传入的参数item是数组,而不是data1这个对象
        this.state = {
            rowData: [
                {key: 's1', data: [data1]},
                {key: 's2', data: [data2]},
                {key: 's3', data: [data3]}
                ]
        }

    }
    _listHeaderComponent =()=> {
        return(
            <View style={{backgroundColor: '#aaaaff'}}>
                <Text>
                    我是listHeader
                </Text>
            </View>
        )
    };
    _listFooterComponent =()=> {
         return(
             <View style={{backgroundColor: '#aaaaff'}}>
                 <Text>
                     我是listFooter
                 </Text>
             </View>
         )
    };
    //参数需要{}修饰,告诉是个对象
    _renderSectionHeader = ({section}) => {
        console.log('_renderSectionHeader' + section.key);
        return(
            <View style={{flex: 1, height: 25, backgroundColor: '#11ffff', justifyContent: 'center'}}>
                <Text style={styles.sectionHeader}>{section.key}</Text>
            </View>
        )
    };
    //参数需要{}修饰,告诉是个对象
    _renderItem =({item})=> {
        console.log('_renderItem' + item[0]);
        return (
        <View style={styles.list}>
            {
                item.map((val, i)=>{
                    return <Row key={i} data={val}/>
                })
            }
        </View>
        )
    };
    _extraUniqueKey =(item)=> {
        return "index"+item;
    };
    render(){
        return(
            <SectionList style={{flex: 1, backgroundColor: '#aaffaa', marginTop: 20}}
                         renderItem={this._renderItem}
                         ListFooterComponent={this._listFooterComponent}
                         ListHeaderComponent={this._listHeaderComponent}
                         renderSectionHeader={this._renderSectionHeader}
                         showsVerticalScrollIndicator={false}
                         keyExtractor = {this._extraUniqueKey}
                         sections={
                             this.state.rowData
                         }>

            </SectionList>
        )
    }
}
const styles = StyleSheet.create({
    list:{
        flexDirection: 'row', //这里的属性很重要,可以学习下flex布局
        flexWrap: 'wrap',
        alignItems: 'flex-start',
        backgroundColor: '#FFFFFF'
    },
    row:{
        backgroundColor: '#FFFFFF',
        justifyContent: 'center',
        // alignItems: 'center',
        width: windowsSize.width/4,
        height: windowsSize.width/4,
    },
    sectionHeader: {
        marginLeft: 10,
        fontSize: 12,
        color: '#787878'
    },
});
AppRegistry.registerComponent('SectionView', ()=>SectionView);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容