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

效果图:


exampleImage.png

最近自己研究了下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=_.cloneDeep(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: this.props.scrollAnimation, itemIndex: 0,sectionIndex: index,viewOffset: (this.props.sectionHeight * (index + 1)) + (this.props.sectionHeaderHeight * index)})
                       }}>
                      <View style={[styles.letterItemView,otherStyle]}>
                          <Text numberOfLines={0} style={[styles.letterText,this.props.letterTextStyle]}>{item}</Text>
                       </View>
                    </TouchableWithoutFeedback>
               )
            })
        }
</View>

当点击每个索引的时候,就会触发sectionList的scrollToLocation方法,最新版本已经修复了点击索引不准确的问题。
遇到点击索引不准确问题,可以试着设置sectionHeight和sectionHeaderHeight
最后中间踩到的坑,做一些经验总结:

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

库地址react-native-sectionlist-contacts

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容