react-native 之 SectionList的使用

目的

项目首页要用RN来写 (类似于iOS 中带有分组的collectionView样式的布局 带一个表头 再带一个tableHeader)

首先我们先决定使用 FlatList还是SectionList (ScrollView 内存消耗太大就先不考虑了 因为有了改进版的FlatList和SectionList所以ListView也不考虑了)

  • FlatList 是0.43版本开始新出的改进版的ListView,性能更优,但是官方说现在可能不够稳定,尚待时间考验。但是它不能够分组/类/区(section)。

  • SectionList 也是0.43版本推出的, 高性能的分组列表组件。而且他还支持吸顶悬浮的效果

好啦, 综上所诉我选择使用SectionList ,现在开始干活吧

先来看下UI给的效果

屏幕快照 2017-07-03 上午9.11.33.png

下面我们就开始干活了!!!!!!!!!!!!

第一步我们先把要显示的样式写好,把SectionList作为子控件,把数据整理好(数据肯定是从接口请求的 这里就不说怎么获取网络请求了)

 render() {
       console.log('render');

       return (
           this.state.order_list?
               <SectionList

                   contentContainerStyle={{  flexDirection: 'row',//设置横向布局
       flexWrap: 'wrap',  justifyContent:'space-between',}} //设置换行显示
                   ListHeaderComponent = {() => this._renderTableHeader()}
                   renderSectionHeader={this._header}
                   renderItem = {this.renderItem}
                   //滑动
                   stickySectionHeadersEnabled ={false}
                   keyExtractor={item => item.title}
                   sections={
                          [{key:'s1',data:this.state.order_list.items}]
                      }
               />
               :
               null
           // </View>




       )
   }
}

   renderItem = ({item}) => {
       console.log(item);
       return(
           <View style={styles.list} >

               {
                   item.map((item, i) => this.renderExpenseItem(item, i))

               }
           </View>

       )
   }

因为我之前是写iOS的,对UItableView的缓存机制比较了解 ,而且app 也比较重视内存消耗所以我觉得这样写虽然实现了效果 但是内存过高是一大弊端,我在想那篇文章他这么写是因为表头他不能成一行显示所以我们来给他整个屏幕的宽度
结果完美如下图 (我这个是完成的项目首页里面用到了ListHeaderComponent 和SectionHeader 还有tem)


屏幕快照 2017-07-03 下午12.04.25.png
屏幕快照 2017-07-03 下午12.04.41.png
屏幕快照 2017-07-03 下午12.04.52.png

因为东西太多所以有些东西都是分成组件来写的,所以这里仅仅是一些主要的源码(不是很清楚)之后会做一个小的Dome 传到git 上去(有些东西可能理解的还不是狠透彻,希望各位大神指教!!!!!)
git 地址 https://github.com/gjjggg/SectionList.git

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    FlatList,
    SectionList,
    TouchableOpacity
} from 'react-native';
import Config  from  '../Tool/Config'
import NetWorking from '../Tool/NetWorking'
import Swiper from 'react-native-swiper'
import JiuGongGe from './JiuGongGe/JiuGongGe'
import PinPaiii  from  './PinPaiTuiJIan/pinPaiTuiJian'
import TuiJianPinTuan from './TuiJianPinTuan/TuiJianPinTuan'
import XianShiMiaoSha from  './XinShiMiaoSha/XianShiMiaoSha'
export default class tuijian extends Component {
    static  defaultProps = {
        dchannel_id:React.PropTypes.string,
    }

    componentDidMount() {
        console.log(this.props.dchannel_id)

        this.fetch();

    }


    // 构造
    constructor(props) {


        super(props);
        // 初始状态
        this.state = {

            dataSource:[
                [
                    {"title":"品牌",'id':'123',
                        item:[
                            {"thumb":"白色AHO-EFR-WDT-00208"},
                            {"thumb":"草绿AHO-EFR-WDT"},
                            {"thumb":"FR-WDT-00208"}]
                    },
                ],[
                    {"title":"颜色",
                        item:[
                            {"thumb":"共色是客户端"},
                            {"thumb":"是滴是滴就-EFR-WDT"},
                            {"thumb":"撒大家打肯德基0208"}
                        ]
                    }
                ]
            ],
            allChildArr:[],
            roll_pic:null,
            roll_goods:null,
            roll_brand:null,
            order_list:null,
            display_list:null,
            cha_cate:null,
            act_ad:null,

        };
    }

    fetch(){
        let url = `${Config.api.baseRootUrl}Channel/content.json?channel_id=${this.props.dchannel_id}`;
        // console.log(this.props.dchannel_id)
        NetWorking.get(url,(data)=>{
            console.log(data)

            let roll_goods,roll_pic,roll_brand,order_list,cha_cate,display_list,act_ad;
            data.map((item,i)=> {

                console.log(item.module);
                if (item.module === 'roll_pic'){
                    // this.setState({
                    //     roll_goods: item,
                    //
                    // })
                    item.items.length==0? null:
                    roll_pic=item
                }
                if (item.module === 'cha_cate'){
                    // this.setState({
                    //     roll_pic: item,
                    //
                    // })
                    item.items.length==0? null: cha_cate = item;
                }
                if (item.module === 'roll_goods'){
                    // this.setState({
                    //     roll_goods: item,
                    //
                    // })
                    item.items.length==0? null:
                    roll_goods=item
                }
                if (item.module === 'roll_tuan'){
                    // this.setState({
                    //     roll_goods: item,
                    //
                    // })
                    item.items.length==0? null:
                    roll_goods=item
                }
                if (item.module === 'display_list'){
                    // this.setState({
                    //     roll_goods: item,
                    //
                    // })
                    item.items.length==0? null:
                    display_list=item
                }

                if (item.module === 'roll_brand'){
                    item.items.length==0? null:
                    roll_brand = item;
                }
                if (item.module === 'act_ad'){
                    item.items.length==0? null:
                    act_ad = item;
                }
                if (item.module === 'order_list'){


                    item.items.length==0? null:
                    order_list = item;
                }
            })

            this.setState({
                roll_goods:roll_goods,
                roll_pic:roll_pic,
                roll_brand:roll_brand,
                order_list:order_list,
                cha_cate:cha_cate,
                act_ad:act_ad,
                display_list:display_list,

            })

        },(error)=>{
            console.log(error);
        });
    }


    renderItem = ({item}) => {
        console.log(item);
        return(
            <TouchableOpacity style={[styles.list]} >
                <Image  source={{uri:item.thumb}}  style={styles.row}  />
                <View style={styles.textViewTitleStyle}>
                    <Text style={styles.textTitleStyle} numberOfLines={2}>
                        {item.title}
                    </Text>
                </View>
                <View style={styles.priceViewStyle}>
                    <Text style={styles.priceTextStle}>
                        ¥{item.marketprice}
                    </Text>
                    <Text style={styles.pricetextKuangstyle} numberOfLines={1}>
                        包邮
                    </Text>
                </View>
            </TouchableOpacity>
        )
    }

    _renderTableHeader =()=>{
        return(
            this.state.order_list ?

                <View style={{backgroundColor:'#ffffff'}}>
                    {
                   this.state.roll_pic ?
                    <Swiper style={tableHeader.swiperStyle}
                            autoplay ={true}
                            height = {SCREEN_WIDTH*0.333}
                            dotColor ="white"
                            activeDotColor = "#ed6d00"
                            autoplayTimeout={1}
                            paginationStyle  = {{ position:'absolute',bottom:5,}}
                    >

                        {this.state.roll_pic.items.map((item,i)=> {

                            return <Image source={{uri: item.img}} style={{width:SCREEN_WIDTH,height:SCREEN_WIDTH*0.333,marginLeft:0}} />

                        })}

                    </Swiper>
                            :null
                    }
                    {
                        this.state.act_ad?
                        <TouchableOpacity style={{ marginTop:10}}   activeOpacity={0.8} onPress={this.props.searchButton}>

                            <Image style={tableHeader.bannerBottom} source={require('../images/icon_home_message_h.png')} />
                        </TouchableOpacity>
                            :null
                    }
                    {
                        this.state.roll_pic?
                        <JiuGongGe cha_cate ={this.state.cha_cate}/>
                         :null
                    }
                    {
                        this.state.roll_goods?
                        <TuiJianPinTuan  roll_goods ={this.state.roll_goods}/>
                            :null
                    }
                    {
                        this.state.display_list?
                        <XianShiMiaoSha display_list={this.state.display_list} />
                            :null
                    }



                    <PinPaiii roll_brand={this.state.roll_brand}/>
                </View>
                :null

        )
    }
    _header = () => {
        return (
            <View style={styles.TuiJianStyleBig}>
                <View style={styles.pinPatTuiJianStyle}>

                    <Image  source={require('../images/title_point_r_left@2x.png')}/>

                    <Text style={{marginLeft:10}}>
                        精选推荐
                    </Text>
                    <Image source={require('../images/title_point_r_right@2x.png')} style={{marginLeft:10}}/>

                </View>
            </View>
        )

    }

    _footer = () => {
        return <Text style={[styles.txt,{backgroundColor:'black'}]}>这是尾部</Text>;
    }
    render() {
        console.log('render');

        return (
            this.state.order_list?
                <SectionList

                    contentContainerStyle={{  flexDirection: 'row',//设置横向布局
        flexWrap: 'wrap',  justifyContent:'space-between',}} //设置换行显示
                    ListHeaderComponent = {() => this._renderTableHeader()}
                    renderSectionHeader={this._header}
                    renderItem = {this.renderItem}
                    //滑动
                    stickySectionHeadersEnabled ={false}
                    keyExtractor={item => item.title}
                    sections={
                           [{key:'s1',data:this.state.order_list.items}]
                       }
                />
                :
                null
            // </View>




        )
    }
}

const tableHeader = StyleSheet.create({
    swiperStyle:{

      //  backgroundColor:'#ed6d00'



    },
    slide1: {
        flex: 1,
        // justifyContent: 'center',
        // flexDirection: 'row',//设置横向布局
        // flexWrap: 'wrap',  //设置换行显示
        // backgroundColor: 'red',
        width:SCREEN_WIDTH,
        height:SCREEN_WIDTH*0.333,

    },
    slide2: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#97CAE5',
    },
    slide3: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#92BBD9',
    },
    bannerBottom:{
        width:SCREEN_WIDTH,
        height:SCREEN_WIDTH*0.2666,

    }


})


const styles = StyleSheet.create({
    container: {
        flex: 1,
        // justifyContent: 'center',
        // alignItems: 'center',
        backgroundColor: '#F5FCFF',
        flexDirection:'row',

    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },

    list: {

        flexDirection: 'row',//设置横向布局
        flexWrap: 'wrap',  //设置换行显示
        alignItems: 'flex-start',
        justifyContent:'space-between',
        width: SCREEN_WIDTH / 2-5,
        paddingBottom:3
    },

    textViewTitleStyle:{

        height:35


    },
   textKuangStyle:{
      backgroundColor:'#ff5b41',
       padding:3,
       borderRadius:5,


   },
    textTitleStyle:{
      fontSize:13,
      padding:3

    },
    priceViewStyle:{
        flexDirection:'row',

    },
    priceTextStle:{
        fontSize:15,
        padding:3,
        color:'#ff8202'

    },
    pricetextKuangstyle:{
        backgroundColor:'#ff8202',
        color:'white',
        marginLeft:5,
        padding:2,
        borderRadius:5,
        fontSize:13,
        height:17,
        marginTop:4


    },
    row: {
        backgroundColor: '#F5FCFF',
        width: SCREEN_WIDTH / 2-5,
        height: SCREEN_WIDTH / 2-5,

        marginLeft:0
    },

    TuiJianStyleBig:{

        flex:1,
        width:SCREEN_WIDTH,
        backgroundColor:'#ededed',
        paddingTop:10
    },
    pinPatTuiJianStyle:{
        width:SCREEN_WIDTH,
        height:SCREEN_WIDTH*0.10666,
        flexDirection:'row',
        justifyContent:'center',
        alignItems:'center',
        flex:1,
        backgroundColor:'#ffffff',

    },
    tuiLeftImageStyle:{


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

推荐阅读更多精彩内容