我正在尝试使用 React 应用程序滚动到每个页面的顶部
I'm trying to scroll to top of each page using react app
我在导航到项目中的另一个页面时遇到问题。它从大约一半开始,然后滚动到页面顶部。我希望它在页面顶部自动打开,然后能够向下滚动以查看页面的其余部分。这是我当前滚动到顶部的代码:
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
您可以使用 window.scrollTo
的 options 版本指定滚动行为。
An enum, the value of which can be one of the following:
- smooth: The scrolling animates smoothly.
- auto: The scrolling happens in a single jump.
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo({
left: 0,
top: 0,
behavior: 'auto', // <-- The scrolling happens in a single jump
});
}, [pathname]);
return null;
}
我在导航到项目中的另一个页面时遇到问题。它从大约一半开始,然后滚动到页面顶部。我希望它在页面顶部自动打开,然后能够向下滚动以查看页面的其余部分。这是我当前滚动到顶部的代码:
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
您可以使用 window.scrollTo
的 options 版本指定滚动行为。
An enum, the value of which can be one of the following:
- smooth: The scrolling animates smoothly.
- auto: The scrolling happens in a single jump.
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo({
left: 0,
top: 0,
behavior: 'auto', // <-- The scrolling happens in a single jump
});
}, [pathname]);
return null;
}