這裏用到了 IntersectionObserver, 關於這個論述阮一峯老師有專門寫到。我這裏就參照這個理論作了個工具 爲了兼容性我引入了npm install intersection-observer; 而後在入口文件import 'intersection-observer'; 而後就能夠開始寫工具了react
useObserve.tsx
export default (ref: React.RefObject<any>, visibleCall, hiddenCall) => {
const intersectionObserver = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio <= 0) {
hiddenCall();
} else {
visibleCall();
}
});
if (ref.current) {
intersectionObserver.observe(ref.current);
}
};
複製代碼
第一個參數傳入要監控的對象
第二個參數傳入一個監控對象進入顯示區域後的回調函數
第三個參數傳入一個監控對象超出顯示區域後的回調函數npm
而後怎麼使用呢?
在要用的頁面 import IntersectionObserver from '...';
在頁面上定義一個div做爲監控對象像下面這個樣子bash
public render(){
return(
...列表
<div ref={this.ref}>加載更多</div>
)
}
複製代碼
我是用的react,在生命週期 componentDidMount 監控一下。函數
public componentDidMount() {
useObserver(this.ref, this.loadMore, this.hidden);
}
private loadMore = () => {
console.log('visible');
}
private hidden = () => {
console.log('hidden');
}
複製代碼
這樣就能夠了工具