**
通讯录右侧字母的点击滚动跳转 计算偏移量,进行组件库源码的改动
**
点击右侧字母导航,SectionList滚动到对应的节点上
- 1.1. 给字母索引列表的item加一个点击事件
- 1.2. 定义_onSectionselect(滚动事件)
_onSectionselect = (key) => {
let offset = key * 20; //点击了那个字母索引,没有section的header的高是20;key为0是即偏移0
const {sections} = this.state;
sections.map((item,index) => {
if(key > index){ //要滚动的距离就是,点击的字母索引之前的所有内容,所以当 点击字母的索引 大于 sections(变量)的索引时;技术要滚动的高度
offset = offset + item.data.length*80 + (item.data.length-1); //每个联系人的item高是60,上下padding各为10;然后每个节点里面有length-1条分割线且高度为1
}
});
//滚动到指定的偏移的位置
this.refs._sectionList.scrollToOffset({animated: true, offset: offset});
};
这里主要计算滚动的偏移量,比如我点击了第一个字母,就需要偏移一个字母的所有数据(item)、节点头部(renderSectionHeader)和分割线的总高度,移除类推。
- 2 修改SectionList源码,添加scrollToOffset方法
注意:SectionList这个列表组件并没有scrollToOffset方法(直接使用会报错:找不到scrollToOffset方法);FlatList中才有,包括scrollToIndex和scrollToEnd也是一样
SectionList的方法有:
FlatList的方法有:
所以,需要参照FlatList里面的scrollToOffset方法,给SectionList这个列表组件手动添加scrollToOffset方法
第一步:其中SectionList的路径为:node_modules/react-native/Libraries/Lists/SectionList.js,代码格式化后大概在343行的位置,修改如下:
//添加scrollToOffset方法
scrollToOffset(params: {animated?: ?boolean, offset: number}) {
if (this._wrapperListRef) {
this._wrapperListRef.scrollToOffset(params);
}
}
即:
第二步:同时还需要修改VirtualizedSectionList的代码,路径在node_modules/react-native/Libraries/Lists/VirtualizedSectionList.js,大概381行处修改如下:
//添加scrollToOffset方法
scrollToOffset(params: {animated?: ?boolean, offset: number}) {
if (this._listRef) {
this._listRef.scrollToOffset(params);
}
}
即:
到此结束,可以点击通讯录右侧的字母进行列表的跳转了