将 div 的当前滚动保存到本地存储,React
Save current scroll of a div to local storage, React
我看过很多关于这个主题的问题,但似乎没有一个符合我的想法。它们通常涉及 window 滚动。我有一个 div,其中的项目可能会溢出,我想记住用户留下的卷轴。我将其保存在本地存储中,但无法获得正确的滚动位置。 (项目以百计)
const ItemHolder = ({
shouldScroll, // this indicates whether or not we should load the previous scroll from the storage
searchParams,
}: ItemHolderProps) => {
const [items, setItems] = useImmer<Item[]>([]);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => { // HERE WE SHOULD GET THE SCROLL VALUE WHEN UNMOUNTING
const scroll = scrollRef.current; // this is because we don't have access to ref.current in unmount
return () => {
if (scroll) {
// doesn't work
const winScroll = scroll.scrollTop;
const height = scroll.scrollHeight - scroll.clientHeight;
const scrolled = winScroll / height;
localStorage.setItem("scroll", String(scrolled));
}
};
}, []);
useEffect(() => {
const scroll = scrollRef.current;
const scrollAmountStorage = localStorage.getItem("scroll");
let scrollTop = 0;
if (scrollAmountStorage) {
scrollTop = Number(scrollAmountStorage);
}
if (shouldScroll && scroll) {
console.log("Scroll top : ", scrollTop);
scroll.scrollTo({ top: scrollTop });
}
}, [shouldScroll]);
return (
<div
// onScroll={(e) => {
// console.log(e);
// }}
ref={scrollRef}
className="grid grid-cols-2 mx-auto p-2 gap-3 overflow-x-auto h-full"
>
{items.map((i) => (
<Item key={i.id} />
))}
</div>
);
};
基本上让我感到困惑的是,没有直观和直接的方法来获取当前滚动然后再次应用它。我发现的所有 SO 答案都将这些类型的计算与 windows.height
等一起使用。
我认为这部分是 un-necessary,除非我完全错过了你的提问
// doesn't work
const height = scroll.scrollHeight - scroll.clientHeight;
const scrolled = winScroll / height;
你在 scrollTop
的正确轨道上
因为上面的例子不能完全重现,包括 Immer 等的使用。我写了一个简单而笨拙的例子来做你想要的。
https://codesandbox.io/s/elegant-leakey-6rqv6?file=/index.html
可以进行大量清理,需要映射到您的代码。
const hugeDiv = document.querySelectorAll("#hugeDiv")[0];
const storedScrollPosition = localStorage.getItem("scrollPos")
? localStorage.getItem("scrollPos")
: 0;
hugeDiv.scrollTo(0, storedScrollPosition);
// Efficient scroll capture with throttle
// Reference: http://www.html5rocks.com/en/tutorials/speed/animations/
let lastKnownScrollPosition = 0;
let ticking = false;
function doSomething(scrollPos) {
// Do something with the scroll position
localStorage.setItem("scrollPos", lastKnownScrollPosition);
}
hugeDiv.addEventListener("scroll", function (e) {
lastKnownScrollPosition = hugeDiv.scrollTop;
if (!ticking) {
window.requestAnimationFrame(function () {
doSomething(lastKnownScrollPosition);
ticking = false;
});
ticking = true;
}
});
一些注意事项
- 您也可以为水平位置存储
scrollLeft
- Incognito 不存储本地存储项目。
我已经为你做了一个非常简单的例子here
我们可以使用 onScroll 事件来处理和获取 div 的当前滚动位置,但我们不想每次都更新状态,所以我们可以创建一个函数来消除滚动事件(因此它会更新用户停止滚动时的状态)
function useDebounce(delay = 500) {
const [data, setData] = useState(null);
const [dataQuery, setDataQuery] = useState(null);
useEffect(() => {
const delayFn = setTimeout(() => setData(dataQuery), delay);
return () => clearTimeout(delayFn);
}, [dataQuery, delay]);
return [data, setDataQuery];
}
我们将这样使用它:
const [scrollPosition, setScrollPosition] = useDebounce();
在我们要存储滚动位置的div上:
<div
ref={scrollRef}
onScroll={({ target }) => setScrollPosition(target.scrollTop)}
/>
然后我们将创建一个 useEffect 来存储每当 scrollPosition
更改时的值:
useEffect(() => {
if (scrollPosition) localStorage.setItem("scrollPosition", scrollPosition);
}, [scrollPosition]);
最后我们将为初始渲染创建 useEffect 以更改滚动位置;
useEffect(() => {
let scrollPosition = localStorage.getItem("scrollPosition");
if (scrollPosition) scrollRef.current.scrollTop = scrollPosition;
}, []);
整体代码应该是这样的;
import { useEffect, useRef, useState } from "react";
function useDebounce(delay = 500) {
const [data, setData] = useState(null);
const [dataQuery, setDataQuery] = useState(null);
useEffect(() => {
const delayFn = setTimeout(() => setData(dataQuery), delay);
return () => clearTimeout(delayFn);
}, [dataQuery, delay]);
return [data, setDataQuery];
}
export default function App() {
const scrollRef = useRef(null);
const [scrollPosition, setScrollPosition] = useDebounce();
useEffect(() => {
let scrollPosition = localStorage.getItem("scrollPosition");
if (scrollPosition) scrollRef.current.scrollTop = scrollPosition;
}, []);
useEffect(() => {
if (scrollPosition) localStorage.setItem("scrollPosition", scrollPosition);
}, [scrollPosition]);
return (
<div className="App">
<div
ref={scrollRef}
style={{ width: "200px", height: "200px", overflow: "auto" }}
onScroll={({ target }) => {
setScrollPosition(target.scrollTop);
}}
>
<div style={{ width: "100%", height: "15000px" }} />
</div>
</div>
);
}
我看过很多关于这个主题的问题,但似乎没有一个符合我的想法。它们通常涉及 window 滚动。我有一个 div,其中的项目可能会溢出,我想记住用户留下的卷轴。我将其保存在本地存储中,但无法获得正确的滚动位置。 (项目以百计)
const ItemHolder = ({
shouldScroll, // this indicates whether or not we should load the previous scroll from the storage
searchParams,
}: ItemHolderProps) => {
const [items, setItems] = useImmer<Item[]>([]);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => { // HERE WE SHOULD GET THE SCROLL VALUE WHEN UNMOUNTING
const scroll = scrollRef.current; // this is because we don't have access to ref.current in unmount
return () => {
if (scroll) {
// doesn't work
const winScroll = scroll.scrollTop;
const height = scroll.scrollHeight - scroll.clientHeight;
const scrolled = winScroll / height;
localStorage.setItem("scroll", String(scrolled));
}
};
}, []);
useEffect(() => {
const scroll = scrollRef.current;
const scrollAmountStorage = localStorage.getItem("scroll");
let scrollTop = 0;
if (scrollAmountStorage) {
scrollTop = Number(scrollAmountStorage);
}
if (shouldScroll && scroll) {
console.log("Scroll top : ", scrollTop);
scroll.scrollTo({ top: scrollTop });
}
}, [shouldScroll]);
return (
<div
// onScroll={(e) => {
// console.log(e);
// }}
ref={scrollRef}
className="grid grid-cols-2 mx-auto p-2 gap-3 overflow-x-auto h-full"
>
{items.map((i) => (
<Item key={i.id} />
))}
</div>
);
};
基本上让我感到困惑的是,没有直观和直接的方法来获取当前滚动然后再次应用它。我发现的所有 SO 答案都将这些类型的计算与 windows.height
等一起使用。
我认为这部分是 un-necessary,除非我完全错过了你的提问
// doesn't work
const height = scroll.scrollHeight - scroll.clientHeight;
const scrolled = winScroll / height;
你在 scrollTop
因为上面的例子不能完全重现,包括 Immer 等的使用。我写了一个简单而笨拙的例子来做你想要的。
https://codesandbox.io/s/elegant-leakey-6rqv6?file=/index.html
可以进行大量清理,需要映射到您的代码。
const hugeDiv = document.querySelectorAll("#hugeDiv")[0];
const storedScrollPosition = localStorage.getItem("scrollPos")
? localStorage.getItem("scrollPos")
: 0;
hugeDiv.scrollTo(0, storedScrollPosition);
// Efficient scroll capture with throttle
// Reference: http://www.html5rocks.com/en/tutorials/speed/animations/
let lastKnownScrollPosition = 0;
let ticking = false;
function doSomething(scrollPos) {
// Do something with the scroll position
localStorage.setItem("scrollPos", lastKnownScrollPosition);
}
hugeDiv.addEventListener("scroll", function (e) {
lastKnownScrollPosition = hugeDiv.scrollTop;
if (!ticking) {
window.requestAnimationFrame(function () {
doSomething(lastKnownScrollPosition);
ticking = false;
});
ticking = true;
}
});
一些注意事项
- 您也可以为水平位置存储
scrollLeft
- Incognito 不存储本地存储项目。
我已经为你做了一个非常简单的例子here
我们可以使用 onScroll 事件来处理和获取 div 的当前滚动位置,但我们不想每次都更新状态,所以我们可以创建一个函数来消除滚动事件(因此它会更新用户停止滚动时的状态)
function useDebounce(delay = 500) {
const [data, setData] = useState(null);
const [dataQuery, setDataQuery] = useState(null);
useEffect(() => {
const delayFn = setTimeout(() => setData(dataQuery), delay);
return () => clearTimeout(delayFn);
}, [dataQuery, delay]);
return [data, setDataQuery];
}
我们将这样使用它:
const [scrollPosition, setScrollPosition] = useDebounce();
在我们要存储滚动位置的div上:
<div
ref={scrollRef}
onScroll={({ target }) => setScrollPosition(target.scrollTop)}
/>
然后我们将创建一个 useEffect 来存储每当 scrollPosition
更改时的值:
useEffect(() => {
if (scrollPosition) localStorage.setItem("scrollPosition", scrollPosition);
}, [scrollPosition]);
最后我们将为初始渲染创建 useEffect 以更改滚动位置;
useEffect(() => {
let scrollPosition = localStorage.getItem("scrollPosition");
if (scrollPosition) scrollRef.current.scrollTop = scrollPosition;
}, []);
整体代码应该是这样的;
import { useEffect, useRef, useState } from "react";
function useDebounce(delay = 500) {
const [data, setData] = useState(null);
const [dataQuery, setDataQuery] = useState(null);
useEffect(() => {
const delayFn = setTimeout(() => setData(dataQuery), delay);
return () => clearTimeout(delayFn);
}, [dataQuery, delay]);
return [data, setDataQuery];
}
export default function App() {
const scrollRef = useRef(null);
const [scrollPosition, setScrollPosition] = useDebounce();
useEffect(() => {
let scrollPosition = localStorage.getItem("scrollPosition");
if (scrollPosition) scrollRef.current.scrollTop = scrollPosition;
}, []);
useEffect(() => {
if (scrollPosition) localStorage.setItem("scrollPosition", scrollPosition);
}, [scrollPosition]);
return (
<div className="App">
<div
ref={scrollRef}
style={{ width: "200px", height: "200px", overflow: "auto" }}
onScroll={({ target }) => {
setScrollPosition(target.scrollTop);
}}
>
<div style={{ width: "100%", height: "15000px" }} />
</div>
</div>
);
}