起因:产品给了一个需求,要求写一个跟微信朋友圈一样,取首字母产生的通讯录标签页,
写了一遍,发现意外的好写
最终效果
数据采用了随机字符串的方法,并且使用数组方法排序,
let data = [];
let title = [];
for (let i = 0; i < 200; i++) {
let s = Math.random().toString(36).substr(2);
data.push(s);
let number = title.indexOf(s.substr(0, 1));
if (number === -1) {
title.push(s.substr(0, 1));
}
}
data.sort();
title.sort();
核心方法就是根据找到其中的索引,跳转位置,通过window.scrollTo,进行跳转,用findIndex来进行查找准确标签位置,进行跳转,
主要计算公式:
需要跳转的高度 = ( 条目高度 * 索引位置 [+ 其他控件的高度,在其之上的控件])
注: 每个条目大小必须已知
{
this.state.title.map((item, position) => {
return <div onClick={() => {
let find = this.state.data.findIndex(obj => obj.substr(0, 1) === item);
window.scrollTo(0, find * 40 + 400);
}}>{item}</div>
})
}