美文网首页React Native学习
react native基于sectionlist实现类似通讯录

react native基于sectionlist实现类似通讯录

作者: 凹凸怪cq | 来源:发表于2018-03-16 16:30 被阅读220次

    最近自己研究了下react native里的sectionlist组件,写了一个类似通讯录功能的三方库组件react-native-sectionlist-contacts,包含了点击右边的索引进行对应的跳转,下面就阐述下这个组件的原理和使用步骤以及当中遇到的问题。

    代码原理

    根据react native的sectionlist文档,需要传入一个数组类型的数据源给sectionlist,不过在此之前,需要定义下你所需要的头部数据有哪些,我这里定下了26个字母加上一个默认其他,具体代码如下:

    constructor(props) {
            super(props);
           //name字段必须,其他可有可无
            let nameData=[
                {name:'阿玛尼',id:'amani',params: ''},
                {name:'OK',id:'ok',params: '123'},
                {name:'天津饭'},
                {name:'%……&'},
                {name:'周星驰'},
                {name:'习大表哥'},
                {name:'不要这样'},
                {name:'V字仇杀队'},
                {name:'拼车'},
                {name:'他妈跌'},
                {name:'淫僧'},
                {name:'钱学森'},
                {name:'宁采臣'},
                {name:'史泰龙'},
                {name:'恐龙'},
                {name:'任达华'},
                {name:'妈咪宝贝'},
                {name:'ing'},
                {name:'康麦隆'},
                {name:'刘德华'},
                {name:'精忠报国'},
                {name:'黄药师'},
                {name:'大叔皮'},
                {name:'布达拉宫'},
                {name:'方世玉'},
                {name:'ET外星人'},
                {name:'程咬金'},
                {name:'**&&&&'},
            ]
            this.state = {
                dataArray: data,
            }
        }
    

    然后通过查找资料,找到一个获取首字母的方法,传入一个字符串,不管是中文还是英文甚至火星文,都能获取到他的首个字母,因为代码比较多,所以还请在这个链接里查询方法文件(getFirstAlphabet.js),之后再render方法里进行渲染:

    <SectionList
         {...this.props}
         style={this.props.SectionListStyle}
         ref={s=>this.sectionList=s}
         keyExtractor={this._keyExtractor}
         sections={delData}
         renderSectionHeader={this._renderSectionHeader}
         renderItem={this._renderItem}
         getItemLayout={(data, index) => ( {length: this.props.sectionHeight, offset: this.props.sectionHeight * index, index} )}
     />
    

    delData是数组数据源,getItemLayout是给出一个预计算,如果能知道每个item的高度的情况下,设置对应的值为此高度,能够很好的提高组件的渲染效果,同时也是后面能够点击索引定位到位置所必须的条件。这里的sectionHeight就是每个item的高度。
    当然此组件也支持自定义头部样式和自定义内容item样式,可在文档里看到,这里不做说明。
    最后就是右边索引的功能实现,我这里做的是给出的数据源里有对应的索引才显示,不然不显示,代码如下:

            let data=this.state.dataArray
            this.props.sectionListData.map((item,index)=>{
                for (let i=0;i<data.length;i++){
                    if (i==data.length-1){
                        data[i].data.push(item)
                        break
                    }else if (data[i].key==makePy(item.name.toUpperCase())){
                        data[i].data.push(item)
                        break
                    }else {
                        continue
                    }
                }
            })
            let delData = []
            let letterData = []
            for (var i in data){
                if (data[i].data.length!=0){
                    delData.push(data[i])
                    letterData.push(data[i].key)
                }
            }
    

    sectionListData是数据源数组,makePy即为获取每个字符串的首字母方法,最后得到的letterData数据即为索引数组,然后绝对定位渲染出索引:

    <View style={[styles.letterView,this.props.letterViewStyle]}>
            {
                letterData.map((item,index)=>{
                     let otherStyle=[]
                     if (index==letterData.length-1){
                        if (item==this.props.otherAlphabet){
                             otherStyle.push({width: 20})
                        }
                     }
                  return(
                        <TouchableWithoutFeedback key={'letter_'+index} onPress=    
                          {()=>{
                               this.sectionList.scrollToLocation({animated: false,itemIndex: 0,sectionIndex: index,viewOffset: this.props.sectionHeight})
                           }}>
                          <View style={[styles.letterItemView,otherStyle]}>
                              <Text numberOfLines={0} style={[styles.letterText,this.props.letterTextStyle]}>{item}</Text>
                           </View>
                        </TouchableWithoutFeedback>
                   )
                })
            }
    </View>
    

    当点击每个索引的时候,就会触发sectionList的scrollToLocation方法,亲测,react native这个sectionList组件有点问题,并不能准确的跳转到特定位置,会有些偏差,网上找了很多资料,有人提供了一个方法,没有测试,大家可自行选择,解决方法如下,修改rn源码:

    scrollToLocation(params: {
        animated?: ?boolean,
        itemIndex: number,
        sectionIndex: number,
        viewPosition?: number,
      }) {
        // 44 = rowItem 的高度
        const rowItemHeight = 44;
    
        // 24 = sectionItem 的高度
        const sectionItemHeight = 24;
    
        // 50 = 头部item 的高度
        const sectionHeaderHeight = 50;
    
        // 1 = rowItem 之间的分割线的高度
        const separatorHeight = 1;
    
        // 当前 section 之前的 section 的 rowItem(分割线) 的总高度 , 默认为头部高度
        let upRowHeight = sectionHeaderHeight;
    
        for (let ii = 0; ii < params.sectionIndex; ii++) {
          // rowItem 的高度 + 分割线的高度 + sectionHeader 的高度,
          upRowHeight += this.props.sections[ii].data.length * rowItemHeight + (this.props.sections[ii].data.length - 1) * separatorHeight + sectionItemHeight;
        }
    
        // 当前需要显示的 rowItem 偏移量   所有rowItem的高度 + 所有分割线的高度
        let downHeight = params.itemIndex * rowItemHeight + params.itemIndex * separatorHeight;
    
        // 滚动到具体的位置
        this._listRef.scrollToOffset({ animated: true, offset: upRowHeight + downHeight })
    }
    

    最后中间踩到的坑,做一些经验总结:

    可能会有大量数据的时候,会有卡顿情况,所以推荐子组件继承PureComponent,本开源组件默认已经做了这个功能,其次,会有遇到下滑加载缓慢,或者直接点击后面的索引到最后的位置会出现白屏等待很久的问题,这种处理方法可以加个initialNumToRender属性,值为数据源的个数,也就是全部渲染出来initialNumToRender={this.state.dataArray.length}

    最后实现的效果图:


    exampleImage.png

    相关文章

      网友评论

      • BUGLittlePC_hh:你好,有没有demo,万分感谢
        凹凸怪cq:有,放在git上了,文章有链接。
      • 无神:你好,你在实际的开发中有没有遇到有的时候列表只选了 initialNumToRender 设置的条数,之后的数据都不再渲染的情况,数据量很大的情况下initialNumToRender = 列表的长度这个方法貌似不妥啊。
        凹凸怪cq:我这没有出现这个问题。是不是其他手机都不行啊,可能是你的页面样式不对呢?还是不能解决的话,加我QQ吧:770580039
        无神:@凹凸怪cq 我现在把list item的继承父类改成purecomponent了,5s上跑了10次左右木有再出现,Android的有待验证!
        凹凸怪cq:都不在渲染的情况没遇到过,如果出现,我建议你不要设置这个属性,或者是RN的版本问题,可以升级或者降级下RN版本在试下。至于后面你说的那个问题,数据量大是会出现一点问题,就是设置了这个属性后,初始进来这个页面的时候会渲染大量组件消耗内存,页面会有一段时间的空白。但是如果不设置这个属性的话,会出现点击右边的索引,比如W这种靠后的索引,会出现到达位置后,有一段时间的空白,这种效果更不好。但是设置了initialNumToRender就不会出现这种情况,只是页面一开始进来的会有一段时间空白,我觉得这点牺牲还是值得。当然如果你有更好的建议,欢迎提出来。

      本文标题:react native基于sectionlist实现类似通讯录

      本文链接:https://www.haomeiwen.com/subject/iqcrqftx.html