[英]Scroll to top when using pagination in React
I am loading data card and when I press pagination buttons, the data changes but screen remains in the same place.我正在加载数据卡,当我按下分页按钮时,数据会发生变化,但屏幕仍然在同一个地方。 How do I scroll to top when button is pressed?
按下按钮时如何滚动到顶部? The application is a SPA so maybe that is causing the issue?
该应用程序是一个 SPA,所以这可能是导致问题的原因?
const getCoinsData = async () => {
try {
const response = await Axios.get(
`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=100&page=${activePage}&sparkline=true&price_change_percentage=1h%2C24h%2C7d`
);
setData(response.data);
setLoading(false);
} catch (e) {
console.log(e);
}
};
Since the application is a SPA, the page is likely not reloading when you move to next page.由于该应用程序是 SPA,因此当您移至下一页时,该页面可能不会重新加载。 You'll have to manually scroll to the top of the component.
您必须手动滚动到组件的顶部。
To do that, add a ref to the wrapper of the content that you want to scroll to the top of:为此,请将 ref 添加到要滚动到顶部的内容的包装器中:
const wrapperRef = useRef(null);
// ... blablabla component stuff
return {
<div ref={wrapperRef}></div>
}
Then just make sure you next page button handler has access to the ref:然后只需确保您的下一页按钮处理程序可以访问参考:
const handleNextPageButtonClick = async () => {
await getNextPage();
wrapperRef.current.scrollIntoView();
}
Another way you could do it is with a useEffect in the component gets the new data on page change另一种方法是使用组件中的 useEffect 获取页面更改的新数据
edit should have updated the dependencies.编辑应该已经更新了依赖项。 I am assuming your list is coming in as a variable named
data
.我假设您的列表作为一个名为
data
的变量进入。 Just add that to the dependency array.只需将其添加到依赖项数组中即可。 You could use your
data
object or your isSuccess
boolean if you have one.如果您有数据,您可以使用您的
data
object 或isSuccess
boolean。
useEffect(()=>{
window.scrollTo({top: 0});
},[data])
Using window.scrollTo({top: 0}) (as suggested by epicmau5time) worked for me, however, I'd suggest using useMemo rather than useEffect.使用 window.scrollTo({top: 0})(如 epicmau5time 所建议)对我有用,但是,我建议使用 useMemo 而不是 useEffect。 I'm working on a SPA as well, and using Pagination.
我也在做一个 SPA,并使用分页。 So I used useMemo and included the currentPage variable as its dependency.
所以我使用了 useMemo 并将 currentPage 变量作为它的依赖项。
useMemo(() => {
window.scrollTo({top: 0})
}, [currentPage])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.