RN-SectionList-實(shí)現(xiàn)含有索引功能的通訊錄

本文內(nèi)容
1膊畴、SectionList 的簡(jiǎn)單使用
2,右側(cè)索引的實(shí)現(xiàn)
3,實(shí)現(xiàn)sectionList按索引滾動(dòng)的方法

5F8363F3-92EA-4231-806B-F2CAA748605C.png

關(guān)于右側(cè)索引滑動(dòng)實(shí)現(xiàn)的問(wèn)題

<View style={styles.sectionItemViewStyle}
                  ref="sectionItemView"
                  onStartShouldSetResponder={()=>true} // 在用戶開(kāi)始觸摸的時(shí)候(手指剛剛接觸屏幕的瞬間),是否愿意成為響應(yīng)者?
                  onMoveShouldSetResponder={()=>true} // :如果View不是響應(yīng)者寸五,那么在每一個(gè)觸摸點(diǎn)開(kāi)始移動(dòng)(沒(méi)有停下也沒(méi)有離開(kāi)屏幕)時(shí)再詢問(wèn)一次:是否愿意響應(yīng)觸摸交互呢梳凛?
                  onResponderGrant={this.responderGrant} // View現(xiàn)在要開(kāi)始響應(yīng)觸摸事件了。這也是需要做高亮的時(shí)候梳杏,使用戶知道他到底點(diǎn)到了哪里
                  onResponderMove={this.responderMove} // 用戶正在屏幕上移動(dòng)手指時(shí)(沒(méi)有停下也沒(méi)有離開(kāi)屏幕)
                  onResponderRelease={this.responderRelease} // 觸摸操作結(jié)束時(shí)觸發(fā)韧拒,比如"touchUp"(手指抬起離開(kāi)屏幕)
            >
                {sectionItem}
            </View>

有三個(gè)方法可以利用
1,用戶手指按下去 (改變背景色)
2十性,用戶手指移動(dòng)(不離開(kāi)屏幕)(獲取移動(dòng)到那個(gè)一個(gè)確定的位置叛溢,進(jìn)而改變sectionList選中的section)
3,用戶手指抬起 (改變背景色)

· onResponderMove(event) 此方法會(huì)返回一個(gè)pageY的參數(shù)劲适,此參數(shù)是當(dāng)前手指在屏幕的Y坐標(biāo)

·右側(cè)索引表的A~Z 每一個(gè)Item的高度都是固定的楷掉,所以根據(jù)pageY和item的高度,可以計(jì)算出當(dāng)前手指在哪個(gè)item的范圍內(nèi)

 /*手指滑動(dòng)霞势,觸發(fā)事件*/
    scrollSectionList(event) {
        const touch = event.nativeEvent.touches[0];

        // 手指滑動(dòng)范圍 從 A-Q  范圍從50 到 50 + sectionItemHeight * cities.length
        if (touch.pageY - statusHeight >= sectionTopBottomHeight && touch.pageY <= statusHeight + sectionTopBottomHeight + sectionItemHeight * cities.length) {

            //touch.pageY 從頂部開(kāi)始烹植,包括導(dǎo)航條 iOS 如此,如果是android 則具體判斷
            const index = (touch.pageY - statusHeight - sectionTopBottomHeight) / sectionItemHeight;

            console.log(parseInt(index));

            // 默認(rèn)跳轉(zhuǎn)到 第 index 個(gè)section  的第 1 個(gè) item
            this.refs.sectionList.scrollToLocation({animated: true, itemIndex: 0, sectionIndex: parseInt(index)});

        }
    }

完整代碼

/**
 * Created by mymac on 2017/8/24.
 */
/**
 * Created by mymac on 2017/8/24.
 */
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    SectionList,
    Dimensions,
    TouchableOpacity,
} from 'react-native';

const {width, height} = Dimensions.get('window');

import cities from './city.json';
const statusHeight = 20;
const rowHeight = 44;
const separatorHeight = 1;
const headerHeight = 24;
const sesctionWidth = 20;
const sectionTopBottomHeight = 50;
const sectionItemHeight = (height - statusHeight - sectionTopBottomHeight * 2) / cities.length;

const touchDownBGColor = '#999999';
const touchUpBGColor = 'transparent';

export default class flatList extends Component {

    constructor(props){
        super(props);

        this.state={
            data: [],
            refreshing: false,
            isTouchDown: false,
        };

        this.renderItem = this.renderItem.bind(this);
        this.separatorComponent = this.separatorComponent.bind(this);
        this.listFooterComponent = this.listFooterComponent.bind(this);
        this.listHeaderComponent = this.listHeaderComponent.bind(this);

        this.sectionItemView = this.sectionItemView.bind(this);
        this.itemLayout = this.itemLayout.bind(this);

        this.responderGrant = this.responderGrant.bind(this);
        this.responderMove = this.responderMove.bind(this);
        this.responderRelease = this.responderRelease.bind(this);
        this.scrollSectionList = this.scrollSectionList.bind(this);
    }

    componentDidMount() {
        setTimeout(()=>{
            this.setState({
                data: cities,
            });

            // 數(shù)據(jù)結(jié)構(gòu)示例
            // { key1: "A", data: [{ name: "阿童木" }, { name: "阿瑪尼" }, { name: "愛(ài)多多" }] },

        }, 2000)
    }

    /*section header*/
    renderSectionHeader(info){
        return (
                <Text style={styles.sectionStyle}>
                    {info.section.key}
                </Text>

        )
    }

    /*row*/
    renderItem(info){
        /*
        * index   0
        * item   { name: "阿童木" }  要顯示的值
        * section  當(dāng)前section 的整個(gè)數(shù)據(jù)
        * */

        return (

            <Text style={styles.rowStyle}>
                {info.item.name}
            </Text>

        )
    }
    /*分割線*/
    separatorComponent(){
        return <View style={styles.separtorStyle}/>
    }

    /*底部組件*/
    listFooterComponent(){
        return this.state.data.length !== 0 ? <View>
                <Text style={styles.sectionHeaderFooterStyle}>我是底部組件</Text>
            </View> : null;
    }

    /*頭部組件*/
    listHeaderComponent(){
        return this.state.data.length !== 0 ? <View>
                <Text style={styles.sectionHeaderFooterStyle}>我是頭部組件</Text>
            </View> : null;
    }

    /*沒(méi)有數(shù)據(jù)時(shí)顯示的組件*/
    listEmptyComponent() {
        return (
            <View style={styles.noDataViewStyle}>
                <Text style={styles.noDataSubViewStyle}>
                    暫時(shí)沒(méi)有數(shù)據(jù),先等2秒
                </Text>
            </View>
        )
    }

    /*刷新*/
    refresh(){
        this.setState({
            refreshing: true,
        });
        setTimeout(()=>{
            this.setState({
                refreshing: false,
            });
        },2000);
    }

    /*用戶手指開(kāi)始觸摸*/
    responderGrant(event){
        this.scrollSectionList(event);

        this.setState({
            isTouchDown: true,
        })
    }

    /*用戶手指在屏幕上移動(dòng)手指愕贡,沒(méi)有停下也沒(méi)有離開(kāi)*/
    responderMove(event){
        this.scrollSectionList(event);

        this.setState({
            isTouchDown: true,
        })
    }

    /*用戶手指離開(kāi)屏幕*/
    responderRelease(event){
        this.setState({
            isTouchDown: false,
        })
    }

    /*手指滑動(dòng)草雕,觸發(fā)事件*/
    scrollSectionList(event) {
        const touch = event.nativeEvent.touches[0];

        // 手指滑動(dòng)范圍 從 A-Q  范圍從50 到 50 + sectionItemHeight * cities.length
        if (touch.pageY - statusHeight >= sectionTopBottomHeight && touch.pageY <= statusHeight + sectionTopBottomHeight + sectionItemHeight * cities.length) {

            //touch.pageY 從頂部開(kāi)始,包括導(dǎo)航條 iOS 如此固以,如果是android 則具體判斷
            const index = (touch.pageY - statusHeight - sectionTopBottomHeight) / sectionItemHeight;

            console.log(parseInt(index));

            // 默認(rèn)跳轉(zhuǎn)到 第 index 個(gè)section  的第 1 個(gè) item
            this.refs.sectionList.scrollToLocation({animated: true, itemIndex: 0, sectionIndex: parseInt(index)});

        }
    }

    /*右側(cè)索引*/
    sectionItemView(){

        const sectionItem = cities.map((item, index)=>{
            return <Text key={index}
                         style={
                             [styles.sectionItemStyle,
                             {backgroundColor: this.state.isTouchDown ? touchDownBGColor : touchUpBGColor}]
                         }
                >
                {item.key}
                </Text>
        });

        return(
            <View style={styles.sectionItemViewStyle}
                  ref="sectionItemView"
                  onStartShouldSetResponder={()=>true} // 在用戶開(kāi)始觸摸的時(shí)候(手指剛剛接觸屏幕的瞬間)墩虹,是否愿意成為響應(yīng)者?
                  onMoveShouldSetResponder={()=>true} // :如果View不是響應(yīng)者憨琳,那么在每一個(gè)觸摸點(diǎn)開(kāi)始移動(dòng)(沒(méi)有停下也沒(méi)有離開(kāi)屏幕)時(shí)再詢問(wèn)一次:是否愿意響應(yīng)觸摸交互呢诫钓?
                  onResponderGrant={this.responderGrant} // View現(xiàn)在要開(kāi)始響應(yīng)觸摸事件了。這也是需要做高亮的時(shí)候篙螟,使用戶知道他到底點(diǎn)到了哪里
                  onResponderMove={this.responderMove} // 用戶正在屏幕上移動(dòng)手指時(shí)(沒(méi)有停下也沒(méi)有離開(kāi)屏幕)
                  onResponderRelease={this.responderRelease} // 觸摸操作結(jié)束時(shí)觸發(fā)尖坤,比如"touchUp"(手指抬起離開(kāi)屏幕)
            >
                {sectionItem}
            </View>
        );
    }

    /*每一項(xiàng)的高度(rowHeight)和其在父組件中的偏移量(offset)和位置(index)
    * length :  當(dāng)前rowItem的高度
    * offset : 當(dāng)前rowItem在父組件中的偏移量(包括rowItem的高度 + 分割線的高度 + section的高度)
    * index  :  當(dāng)前rowItem的位置
    *
    * 如果需要手動(dòng)的跳轉(zhuǎn)。則必須實(shí)現(xiàn)此方法
    * */
    itemLayout(data, index) {
        return {length: rowHeight, offset: (rowHeight + separatorHeight) * index + headerHeight, index};
    }

    // http://www.reibang.com/p/09dd60d7b34f

    render() {

        return (
            <View style={{flex: 1, marginTop: statusHeight}}>

                <SectionList
                    ref="sectionList"
                    renderSectionHeader={this.renderSectionHeader} // sectionHeader
                    renderItem={this.renderItem} // rowItem
                    sections={this.state.data} // 數(shù)據(jù)源
                    // getItemLayout={this.itemLayout} // 在知道高度的情況下闲擦,得到每個(gè)item的位置 , 由于我改了源碼慢味,在源碼中跳轉(zhuǎn)指定了位置信息场梆,此處不實(shí)現(xiàn)該方法
                    keyExtractor={(item, index)=> item.code} // 每個(gè)item都有唯一的key
                    ItemSeparatorComponent={this.separatorComponent} // 分割線
                    ListHeaderComponent={this.listHeaderComponent} // 頭部組件
                    ListFooterComponent={this.listFooterComponent} // 尾部組件
                    ListEmptyComponent={this.listEmptyComponent()} // 沒(méi)有數(shù)據(jù)時(shí)顯示的組件
                    refreshing={this.state.refreshing} // 是否刷新 ,自帶刷新控件
                    onRefresh={()=>{
                              this.refresh();
                          }} // 刷新方法,寫了此方法纯路,下拉才會(huì)出現(xiàn)  刷新控件或油,使用此方法必須寫 refreshing
                    // horizontal={true}
                />

                {this.sectionItemView()}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    sectionStyle:{
        color: 'black',
        backgroundColor: '#f5f5f5',
        paddingLeft: 20,
        height: headerHeight,
        lineHeight: headerHeight,
    },
    rowStyle:{
        height: rowHeight,
        lineHeight: rowHeight,
        width: width,
        marginLeft: 30,
        color: 'black',
    },
    separtorStyle:{
        height: separatorHeight,
        backgroundColor: '#f5f5f5'
    },
    sectionHeaderFooterStyle:{
        alignItems: 'center',
        textAlign: 'center',
        height: sectionTopBottomHeight,
        backgroundColor: 'red',
        lineHeight: sectionTopBottomHeight,
    },
    noDataViewStyle:{
        backgroundColor: 'red',
        flex: 1,
        height: height
    },
    noDataSubViewStyle:{
        alignItems: 'center',
        textAlign: 'center',
        lineHeight: height,
        color: 'white'
    },
    sectionItemViewStyle:{
        position: 'absolute',
        width: sesctionWidth,
        height: height - statusHeight,
        right: 0,
        top: 0,
        paddingTop: sectionTopBottomHeight,
        paddingBottom: sectionTopBottomHeight,
    },
    sectionItemStyle:{
        textAlign: 'center',
        alignItems: 'center',
        height: sectionItemHeight,
        lineHeight: sectionItemHeight
    },

});

AppRegistry.registerComponent('RNProjectTestApp', () => flatList);

數(shù)據(jù)結(jié)構(gòu),摘取其中部分

其中 key 這個(gè)字段 驰唬,最好是帶上顶岸,且必須是唯一的
data 這個(gè)字段是必須的,源碼里面就是 .data 出來(lái)得到數(shù)據(jù)的

[
    {
        "key": "A",
        "data": [
            {
                "name": "阿拉善盟",
            }
        ]
    },
    {
        "key": "B",
        "data": [
            {
                "name": "北京市",
            }
        ]
    },
    {
        "key": "C",
        "data": [
            {
                "name": "承德市",
            }
        ]
    },
    {
        "key": "D",
        "data": [
            {
                "name": "大同市",
            }
        ]
    }
]

重中之重的重點(diǎn):

  this.refs.sectionList.scrollToLocation({animated: true, itemIndex: 0, sectionIndex: parseInt(index)});

sectionList 只包含一個(gè) scrollToLocation 的方法叫编,實(shí)現(xiàn)方法
路徑:

node_modules/react-native/Libraries/Lists/VirtualizedSectionList.js,代碼格式化后大概在150行的位置

  scrollToLocation(params: {
    animated?: ?boolean,
    itemIndex: number,
    sectionIndex: number,
    viewPosition?: number,
  }) {
    
    let index = params.itemIndex + 1;
    for (let ii = 0; ii < params.sectionIndex; ii++) {
      index += this.props.sections[ii].data.length + 2;
    }

    const toIndexParams = {
      ...params,
      index,
    };
    this._listRef.scrollToIndex(toIndexParams);
}

本人腦子不夠用辖佣,實(shí)在沒(méi)有看懂這里面的邏輯,for 里面的 +2 搓逾,實(shí)在是沒(méi)有看懂卷谈,而且用了這個(gè) scrollToLocation 方法,并不能真正的跳轉(zhuǎn)到我想跳轉(zhuǎn)的位置霞篡,測(cè)試了好幾天世蔗,很尷尬??

本人的解決辦法,重新改造了新的 scrollToLocation 的方法朗兵,

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;

    // 當(dāng)前 section 之前的 section 的 rowItem(分割線) 的總高度 污淋, 默認(rèn)為頭部高度
    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;
    }

    // 當(dāng)前需要顯示的 rowItem 偏移量   所有rowItem的高度 + 所有分割線的高度
    let downHeight = params.itemIndex * rowItemHeight + params.itemIndex * separatorHeight;

    // 滾動(dòng)到具體的位置
    this._listRef.scrollToOffset({ animated: true, offset: upRowHeight + downHeight })
}

·原本的 scrollToLocation 的方法內(nèi)部是根據(jù) scrollToIndex 來(lái)跳轉(zhuǎn)的

·我的 scrollToLocation 的方法內(nèi)部是根據(jù) scrollToOffset 來(lái)跳轉(zhuǎn)的

由于改了源碼余掖,所以缺點(diǎn)很明顯寸爆。。盐欺。而昨。

但我是實(shí)在理解不了原來(lái)的 scrollToLocation 方法里面的邏輯,希望有大神能注意到這里的話找田,麻煩給講解下??~O(∩_∩)O謝謝

??????????????????????????????????

根據(jù)評(píng)論的大神們說(shuō):多些一個(gè) viewOffset就可以了歌憨,本人沒(méi)試~

this.sectionList.scrollToLocation({animated: true,sectionIndex:index, itemIndex:0, viewOffset:26})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市墩衙,隨后出現(xiàn)的幾起案子务嫡,更是在濱河造成了極大的恐慌,老刑警劉巖漆改,帶你破解...
    沈念sama閱讀 219,270評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件心铃,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡挫剑,警方通過(guò)查閱死者的電腦和手機(jī)去扣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)樊破,“玉大人愉棱,你說(shuō)我怎么就攤上這事唆铐。” “怎么了奔滑?”我有些...
    開(kāi)封第一講書人閱讀 165,630評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵艾岂,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我朋其,道長(zhǎng)王浴,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,906評(píng)論 1 295
  • 正文 為了忘掉前任梅猿,我火速辦了婚禮氓辣,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘袱蚓。我一直安慰自己钞啸,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布癞松。 她就那樣靜靜地躺著爽撒,像睡著了一般入蛆。 火紅的嫁衣襯著肌膚如雪响蓉。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,718評(píng)論 1 305
  • 那天哨毁,我揣著相機(jī)與錄音枫甲,去河邊找鬼。 笑死扼褪,一個(gè)胖子當(dāng)著我的面吹牛想幻,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播话浇,決...
    沈念sama閱讀 40,442評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼脏毯,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了幔崖?” 一聲冷哼從身側(cè)響起食店,我...
    開(kāi)封第一講書人閱讀 39,345評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎赏寇,沒(méi)想到半個(gè)月后吉嫩,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,802評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡嗅定,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評(píng)論 3 337
  • 正文 我和宋清朗相戀三年自娩,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片渠退。...
    茶點(diǎn)故事閱讀 40,117評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡忙迁,死狀恐怖脐彩,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情动漾,我是刑警寧澤丁屎,帶...
    沈念sama閱讀 35,810評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站旱眯,受9級(jí)特大地震影響晨川,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜删豺,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評(píng)論 3 331
  • 文/蒙蒙 一共虑、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧呀页,春花似錦妈拌、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,011評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至丸氛,卻和暖如春培愁,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背缓窜。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,139評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工定续, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人禾锤。 一個(gè)月前我還...
    沈念sama閱讀 48,377評(píng)論 3 373
  • 正文 我出身青樓私股,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親恩掷。 傳聞我的和親對(duì)象是個(gè)殘疾皇子倡鲸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容