在本篇文章你将会学到:css
IntersectionObserver API
的用法,以及如何兼容。React Hook
中实现无限滚动。当你使用滚动做为发现数据的主要方法时,它可能使你的用户在网页上停留更长时间并提高用户参与度。随着社交媒体的流行,大量的数据被用户消费。无线滚动提供了一个高效的方法让用户浏览海量信息,而没必要等待页面的预加载。前端
如何构建一个体验良好的无限滚动,是每一个前端不管是项目或面试都会碰到的一个课题。vue
本文的原版实现来自:Creating Infinite Scroll with 15 Elementsnode
关于无限滚动,早期的解决方案基本都是依赖监听scroll事件:react
function fetchData() {
fetch(path).then(res => doSomeThing(res.data));
}
window.addEventListener('scroll', fetchData);
复制代码
而后计算各类.scrollTop()
、.offset().top
等等。git
手写一个也是很是枯燥。并且:github
scroll
事件会频繁触发,所以咱们还须要手动节流。DOM
,容易形成卡顿。IntersectionObserver API
,在与
Vue
、
React
这类数据驱动视图的框架后,无限滚动的通用方案就出来了。
IntersectionObserver
const box = document.querySelector('.box');
const intersectionObserver = new IntersectionObserver((entries) => {
entries.forEach((item) => {
if (item.isIntersecting) {
console.log('进入可视区域');
}
})
});
intersectionObserver.observe(box);
复制代码
敲重点: IntersectionObserver API是异步的,不随着目标元素的滚动同步触发,性能消耗极低。面试
IntersectionObserverEntry
对象IntersectionObserverEntry
对象vue-cli
callback
函数被调用时,会传给它一个数组,这个数组里的每一个对象就是当前进入可视区域或者离开可视区域的对象(IntersectionObserverEntry
对象)后端
这个对象有不少属性,其中最经常使用的属性是:
target
: 被观察的目标元素,是一个 DOM 节点对象isIntersecting
: 是否进入可视区域intersectionRatio
: 相交区域和目标元素的比例值,进入可视区域,值大于0,不然等于0options
调用IntersectionObserver
时,除了传一个回调函数,还能够传入一个option
对象,配置以下属性:
threshold
: 决定了何时触发回调函数。它是一个数组,每一个成员都是一个门槛值,默认为[0],即交叉比例(intersectionRatio)达到0时触发回调函数。用户能够自定义这个数组。好比,[0, 0.25, 0.5, 0.75, 1]就表示当目标元素 0%、25%、50%、75%、100% 可见时,会触发回调函数。root
: 用于观察的根元素,默认是浏览器的视口,也能够指定具体元素,指定元素的时候用于观察的元素必须是指定元素的子元素rootMargin
: 用来扩大或者缩小视窗的的大小,使用css的定义方法,10px 10px 30px 20px表示top、right、bottom 和 left的值const io = new IntersectionObserver((entries) => {
console.log(entries);
}, {
threshold: [0, 0.5],
root: document.querySelector('.container'),
rootMargin: "10px 10px 30px 20px",
});
复制代码
observer
observer.observer(nodeone); //仅观察nodeOne
observer.observer(nodeTwo); //观察nodeOne和nodeTwo
observer.unobserve(nodeOne); //中止观察nodeOne
observer.disconnect(); //没有观察任何节点
复制代码
React Hook
中使用IntersectionObserver
在看Hooks
版以前,来看正常组件版的:
class SlidingWindowScroll extends React.Component {
this.$bottomElement = React.createRef();
...
componentDidMount() {
this.intiateScrollObserver();
}
intiateScrollObserver = () => {
const options = {
root: null,
rootMargin: '0px',
threshold: 0.1
};
this.observer = new IntersectionObserver(this.callback, options);
this.observer.observe(this.$bottomElement.current);
}
render() {
return (
<li className='img' ref={this.$bottomElement}>
)
}
复制代码
众所周知,React 16.x
后推出了useRef
来替代原有的createRef
,用于追踪DOM节点。那让咱们开始吧:
实现一个组件,能够显示具备15个元素的固定窗口大小的n个项目的列表: 即在任什么时候候,无限滚动n元素上也仅存在15个DOM
节点。
relative/absolute
定位来肯定滚动位置ref
: top/bottom
来决定向上/向下滚动的渲染与否useState
声明状态变量咱们开始编写组件SlidingWindowScrollHook
:
const THRESHOLD = 15;
const SlidingWindowScrollHook = (props) => {
const [start, setStart] = useState(0);
const [end, setEnd] = useState(THRESHOLD);
const [observer, setObserver] = useState(null);
// 其它代码...
}
复制代码
useState的简单理解:
const [属性, 操做属性的方法] = useState(默认值);
复制代码
start
:当前渲染的列表第一个数据,默认为0end
: 当前渲染的列表最后一个数据,默认为15observer
: 当前观察的视图ref
元素useRef
定义追踪的DOM
元素const $bottomElement = useRef();
const $topElement = useRef();
复制代码
正常的无限向下滚动只需关注一个dom元素,但因为咱们是固定15个dom
元素渲染,须要判断向上或向下滚动。
useEffect
请配合注释食用:
useEffect(() => {
// 定义观察
intiateScrollObserver();
return () => {
// 放弃观察
resetObservation()
}
},[end]) //由于[end] 是同步刷新,这里用一个就好了。
// 定义观察
const intiateScrollObserver = () => {
const options = {
root: null,
rootMargin: '0px',
threshold: 0.1
};
const Observer = new IntersectionObserver(callback, options)
// 分别观察开头和结尾的元素
if ($topElement.current) {
Observer.observe($topElement.current);
}
if ($bottomElement.current) {
Observer.observe($bottomElement.current);
}
// 设初始值
setObserver(Observer)
}
// 交叉观察的具体回调,观察每一个节点,并对实时头尾元素索引处理
const callback = (entries, observer) => {
entries.forEach((entry, index) => {
const listLength = props.list.length;
// 向下滚动,刷新数据
if (entry.isIntersecting && entry.target.id === "bottom") {
const maxStartIndex = listLength - 1 - THRESHOLD; // 当前头部的索引
const maxEndIndex = listLength - 1; // 当前尾部的索引
const newEnd = (end + 10) <= maxEndIndex ? end + 10 : maxEndIndex; // 下一轮增长尾部
const newStart = (end - 5) <= maxStartIndex ? end - 5 : maxStartIndex; // 在上一轮的基础上计算头部
setStart(newStart)
setEnd(newEnd)
}
// 向上滚动,刷新数据
if (entry.isIntersecting && entry.target.id === "top") {
const newEnd = end === THRESHOLD ? THRESHOLD : (end - 10 > THRESHOLD ? end - 10 : THRESHOLD); // 向上滚动尾部元素索引不得小于15
let newStart = start === 0 ? 0 : (start - 10 > 0 ? start - 10 : 0); // 头部元素索引最小值为0
setStart(newStart)
setEnd(newEnd)
}
});
}
// 中止滚动时放弃观察
const resetObservation = () => {
observer && observer.unobserve($bottomElement.current);
observer && observer.unobserve($topElement.current);
}
// 渲染时,头尾ref处理
const getReference = (index, isLastIndex) => {
if (index === 0)
return $topElement;
if (isLastIndex)
return $bottomElement;
return null;
}
复制代码
const {list, height} = props; // 数据,节点高度
const updatedList = list.slice(start, end); // 数据切割
const lastIndex = updatedList.length - 1;
return (
<ul style={{position: 'relative'}}>
{updatedList.map((item, index) => {
const top = (height * (index + start)) + 'px'; // 基于相对 & 绝对定位 计算
const refVal = getReference(index, index === lastIndex); // map循环中赋予头尾ref
const id = index === 0 ? 'top' : (index === lastIndex ? 'bottom' : ''); // 绑ID
return (<li className="li-card" key={item.key} style={{top}} ref={refVal} id={id}>{item.value}</li>);
})}
</ul>
);
复制代码
App.js
:
import React from 'react';
import './App.css';
import { SlidingWindowScrollHook } from "./SlidingWindowScrollHook";
import MY_ENDLESS_LIST from './Constants';
function App() {
return (
<div className="App">
<h1>15个元素实现无限滚动</h1>
<SlidingWindowScrollHook list={MY_ENDLESS_LIST} height={195}/>
</div>
);
}
export default App;
复制代码
定义一下数据 Constants.js
:
const MY_ENDLESS_LIST = [
{
key: 1,
value: 'A'
},
{
key: 2,
value: 'B'
},
{
key: 3,
value: 'C'
},
// 中间就不贴了...
{
key: 45,
value: 'AS'
}
]
复制代码
SlidingWindowScrollHook.js
:
import React, { useState, useEffect, useRef } from "react";
const THRESHOLD = 15;
const SlidingWindowScrollHook = (props) => {
const [start, setStart] = useState(0);
const [end, setEnd] = useState(THRESHOLD);
const [observer, setObserver] = useState(null);
const $bottomElement = useRef();
const $topElement = useRef();
useEffect(() => {
intiateScrollObserver();
return () => {
resetObservation()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
},[start, end])
const intiateScrollObserver = () => {
const options = {
root: null,
rootMargin: '0px',
threshold: 0.1
};
const Observer = new IntersectionObserver(callback, options)
if ($topElement.current) {
Observer.observe($topElement.current);
}
if ($bottomElement.current) {
Observer.observe($bottomElement.current);
}
setObserver(Observer)
}
const callback = (entries, observer) => {
entries.forEach((entry, index) => {
const listLength = props.list.length;
// Scroll Down
if (entry.isIntersecting && entry.target.id === "bottom") {
const maxStartIndex = listLength - 1 - THRESHOLD; // Maximum index value `start` can take
const maxEndIndex = listLength - 1; // Maximum index value `end` can take
const newEnd = (end + 10) <= maxEndIndex ? end + 10 : maxEndIndex;
const newStart = (end - 5) <= maxStartIndex ? end - 5 : maxStartIndex;
setStart(newStart)
setEnd(newEnd)
}
// Scroll up
if (entry.isIntersecting && entry.target.id === "top") {
const newEnd = end === THRESHOLD ? THRESHOLD : (end - 10 > THRESHOLD ? end - 10 : THRESHOLD);
let newStart = start === 0 ? 0 : (start - 10 > 0 ? start - 10 : 0);
setStart(newStart)
setEnd(newEnd)
}
});
}
const resetObservation = () => {
observer && observer.unobserve($bottomElement.current);
observer && observer.unobserve($topElement.current);
}
const getReference = (index, isLastIndex) => {
if (index === 0)
return $topElement;
if (isLastIndex)
return $bottomElement;
return null;
}
const {list, height} = props;
const updatedList = list.slice(start, end);
const lastIndex = updatedList.length - 1;
return (
<ul style={{position: 'relative'}}>
{updatedList.map((item, index) => {
const top = (height * (index + start)) + 'px';
const refVal = getReference(index, index === lastIndex);
const id = index === 0 ? 'top' : (index === lastIndex ? 'bottom' : '');
return (<li className="li-card" key={item.key} style={{top}} ref={refVal} id={id}>{item.value}</li>);
})}
</ul>
);
}
export { SlidingWindowScrollHook };
复制代码
以及少量样式:
.li-card {
display: flex;
justify-content: center;
list-style: none;
box-shadow: 2px 2px 9px 0px #bbb;
padding: 70px 0;
margin-bottom: 20px;
border-radius: 10px;
position: absolute;
width: 80%;
}
复制代码
而后你就能够慢慢耍了。。。
IntersectionObserver
不兼容Safari
?
莫慌,咱们有polyfill
版
项目源地址:github.com/roger-hiro/…
参考文章:
若是你以为这篇内容对你挺有启发,我想邀请你帮我三个小忙: