問題描述
一個常見的頁面布局:頂部固定導航欄,主內容區有四個欄目 A、B、C、D。點擊 A 錨點跳轉到 A 並讓 A 按鈕高亮;點擊 B 同理;而在主容器內手動滾動時,滾到哪個模塊,對應的導航按鈕就該跟著高亮。用 jQuery 時代這是理所當然的寫法,但換到組件化開發中,滾動事件的高頻觸發就成了必須正視的性能問題。
解決方案概覽
關鍵有兩點:一是對 onScroll 回調做函數節流(throttle),二是把狀態變化通過容器組件逐層下傳到展示組件。
頁面結構大致如下:
<div
className={style.main}
id="main"
ref={(main) => { this.main = main; }}
onScroll={
(/detail/.test(this.props.location.pathname))
? (() => this.throttle()())
: null
}
>
{this.props.children}
<Footer />
</div>
在 main 組件上綁定 onScroll,事件觸發時調用 action,再經 Redux 把狀態變化傳遞給子組件。
滾動事件處理函數
handleScroll() {
const { changeScrollFlag } = this.props.actions;
// 根據滾動距離修改 TitleBox 的樣式
// 取得各區域的 offsetTop(減去頂部導航高度 121px)作為比較基準
const {
basicinformation, holderinformation, mainpeople, changerecord
} = {
basicinformation: document.getElementById('basicinformation').offsetTop - 121,
holderinformation: document.getElementById('holderinformation').offsetTop - 121,
mainpeople: document.getElementById('mainpeople').offsetTop - 121,
changerecord: document.getElementById('changerecord').offsetTop - 121,
};
if (window.screen.availHeight > this.main.scrollTop) {
document.getElementById('gototop').style.display = 'none';
} else {
document.getElementById('gototop').style.display = 'block';
}
// 用 main 的 scrollTop 與各區域 offsetTop 比較,
// 比較結果觸發 action,改變 TitleBox 組件樣式
if (this.main.scrollTop < holderinformation) {
// 基礎信息區域
if (basicinformation === -121) {
// 基礎信息模塊不存在,不做處理
return;
}
changeScrollFlag(1);
return;
} else if (this.main.scrollTop < mainpeople) {
// 股東信息區域
changeScrollFlag(2);
if (holderinformation === -121) {
// 股東信息欄目不存在時,不應強行高亮它,
// 回退到上一個按鈕
changeScrollFlag(1);
return;
}
return;
} else if (this.main.scrollTop < changerecord) {
// 主要人員區域
changeScrollFlag(3);
if (mainpeople === -121) {
changeScrollFlag(2);
if (holderinformation === -121) {
changeScrollFlag(1);
return;
}
return;
}
return;
} else if (this.main.scrollTop > changerecord) {
// 變更記錄區域,處理邏輯同上
changeScrollFlag(4);
if (changerecord === -121) {
changeScrollFlag(3);
if (mainpeople === -121) {
changeScrollFlag(2);
if (holderinformation === -121) {
changeScrollFlag(1);
return;
}
return;
}
return;
}
return;
}
}
其中 changeScrollFlag() 是 action 處理函數。這段邏輯著重處理了一類實際問題:某個欄目在數據中不存在(offsetTop 為 -121)時,不能盲目高亮一個不存在的按鈕,而應回退到上一個存在的欄目。
核心:函數節流
throttle() {
// onScroll 函數節流
let previous = 0; // 上一次調用 onScroll 的時間點,初始為 0
let timeout;
const wait = 250; // 250 毫秒觸發一次
return () => {
const now = Date.now();
const remaining = wait - (now - previous);
if (remaining <= 0) {
if (timeout) {
window.clearTimeout(timeout);
}
previous = now;
timeout = null;
this.handleScroll();
} else if (!timeout) {
timeout = window.setTimeout(this.handleScroll, wait);
}
};
}
思路並不複雜:節流函數返回一個閉包,內部維護上次執行時間戳。若距上次執行已超過 wait,立刻清理定時器並執行;否則保證有一個延遲任務掛在隊列裡。這樣就把高頻的 scroll 事件壓縮為固定頻率的執行,避免每一次像素級滾動都觸發一整套 offsetTop 讀取與 action 分發。
子組件接收 action
二級容器型組件接收 action,再通過 props 傳遞給三級展示型組件。要在 componentWillReceiveProps 中接住這個變化。
這裡有個非常容易犯的錯誤:在 componentWillReceiveProps 中使用 this.props 是拿不到新 props 的,因為新的 props 是通過該生命週期函數自身的參數傳入的。
componentWillReceiveProps(nextProps) {
// 接收到 Main 組件 onScroll 事件改變 activebtn 的 index,
// 並設置為本組件的 state
this.setState({
activebtn: nextProps.scrollFlag.scrollIndex,
});
}
state 中的 activebtn 是一個數字,決定高亮第幾個按鈕。
更改導航條樣式
這裡用到 React 生態中的 classnames 庫來做條件類名拼接:
<span
className={classnames({
[style.informationactive]: (this.state.activebtn === 1),
})}
onClick={() => this.handleClick(1, 'basicinformation')}
>
至此,一次「頂層組件觸發事件 → 函數節流 → 狀態逐層下傳 → 底層展示組件響應」的完整閉環就完成了。
幾點前端開發的經驗總結
總體來看,性能優化在組件化開發中往往不是靠某個「黑科技」,而是靠對事件頻次、渲染範圍、狀態流向這三件事的精確控制。