開發(fā)思路解析
- 實現(xiàn)效果赤赊,永遠只渲染在可視區(qū)域的DOM數(shù)據(jù)
- 計算容器展示所有數(shù)據(jù)的時候的高度
- 滾動計算動態(tài)顯示的開始下標和結(jié)束下標
- slice截取顯示的數(shù)據(jù), 數(shù)據(jù)整體transformY之前數(shù)據(jù)的高度
- 瀑布流布局的情況,對不同的列計算高度省咨,最大高度為容器高度
滾動過程中計算可視區(qū)域到滾動容器頂部的距離有一定難度
模擬數(shù)據(jù)须眷,固定高度50一行
createMockData = () => {
let data = [];
for (var i = 1; i < 10001; i++) {
data.push(`${i}: 第${i}個>>>>>>>>>>>>>>>>>>>>>>`)
}
this.setState({
mockData: data
})
this.refs.scrollBody.style.height = 10000 * 50 + "px";
const canSeeNums = Math.ceil(Number(this.refs.wrrapCpntainer.style.height.split("px")[0]) / 50) + 2;
this.setState({
tail: canSeeNums,
canSeeNums: canSeeNums, // 可展示的數(shù)量+2
itemHeight: 50
})
}
滾動動態(tài)計算 head、tail石咬,展示的節(jié)點開始結(jié)束
handSrcoll = (e) => {
if (e.target.scrollTop) {
this.setState({
head: Math.ceil((e.target.scrollTop - this.state.itemHeight + 10) / this.state.itemHeight),
tail: Math.ceil(e.target.scrollTop / this.state.itemHeight) + 11
})
} else {
this.setState({
head: 0,
tail: this.state.canSeeNums
})
}
}
deBounce = (fn, timeOut = 100) => {
let setTime;
return function (...args) {
let flag = true;
if (flag) {
fn.apply(this, args);
}
setTime = setTimeout(() => {
flag = false;
clearTimeout(setTime)
}, timeOut)
}
}
結(jié)構(gòu)
如果不是固定高度的行,需要動態(tài)計算之前數(shù)據(jù)占據(jù)的高度卖哎,在設置transformY
給滾動加上防抖避免觸發(fā)過多的判斷
<div
style={{
width: 300, height: 500,
border: "1px solid #ddd",
overflowY: "scroll", margin: "20px auto"
}}
ref="wrrapCpntainer"
onScroll={this.deBounce(this.handleScroll)}
>
{/** 滾動容器 */}
<div ref="scrollBody">
<div
style={{
transform:
`translateY(${(head * itemHeight)}px)`
}}
>
{(renderData.slice(head, tail)).map((item) => (
<div
style={{
height: 50, textAlign: "center", borderBottom: "1px solid #ddd", lineHeight: "50px",
}}
>
{item}
</div>
))}
</div>
</div>
</div>