【发布时间】:2021-03-19 00:47:14
【问题描述】:
我今天遇到了最奇怪的问题。我的代码(大部分已被删除)基本上包括以下内容:
const Element: React.FC<any> = (props: any) => {
const scrollRef = React.useRef<any>(null);
.
.
.
const rescrollTrigger = () => {
setTimeout(() => { /* Retry for 10 seconds to scroll the content to match the stored value, unless the user has scrolled since then */
const cb = (tries: number) => {
if (tries > 100)
return;
if (!scrollRef.current) {
setTimeout(cb, 100, [Number(tries) + 1]);
return;
}
scrollRef.current.getScrollElement().then((element: any) => {
var scrollHeight: any = window.sessionStorage.getItem(thisPath + "/scrollheight");
var scrollTop: any = window.sessionStorage.getItem(thisPath + "/scrolltop");
if (!scrollHeight || !scrollTop)
return;
scrollHeight = +scrollHeight;
scrollTop = +scrollTop;
if (element.scrollHeight == scrollHeight)
scrollRef.current.scrollToPoint(0, scrollTop);
else
setTimeout(cb, 100, [Number(tries) + 1]);
}).catch(() => {
setTimeout(cb, 100, [Number(tries) + 1]);
})
};
window.requestAnimationFrame(() => {
cb(1);
});
});
};
const saveScrollPosition = () => {
console.log("saveScrollPosition", scrollRef.current);
try {
scrollRef.current.getScrollElement().then((element: any) => {
console.log("Saving scroll position");
window.sessionStorage.setItem(thisPath + "/scrolltop", String(element.scrollTop));
window.sessionStorage.setItem(thisPath + "/scrollheight", String(element.scrollHeight));
});
} catch (err) {console.log("Error saving scroll position", err)}
};
return (
<IonPage>
<IonContent fullscreen ref={scrollRef} scrollEvents={true} onIonScrollEnd={e => saveScrollPosition()}>
.
.
.
}
我只是想为内容实例创建一个引用(在挂钩中),以便我可以根据需要保存和重置滚动位置。
此代码运行良好,但由于某种原因,如果在内容元素上设置了 ref,则停止触发任何滚动事件。我试过onIonScroll 和onIonScrollEnd。如果设置了 ref,则两者都不起作用。删除ref={scrollRef} 开始触发滚动事件。我正在使用 Ionic 6.12.2,并且最近刚刚从以前的版本升级(我不知道它是什么)。
所以我的问题是:这是 Ionic 中的错误吗?或者如果没有,应该如何修复代码?我尝试不设置 ref 并仅使用从滚动事件返回的目标,这允许我保存位置,但它不保留能够稍后重置滚动位置的引用。
【问题讨论】:
标签: reactjs ionic-framework scroll react-hooks