实现上述功能的步骤如下:
-
安装必要的依赖包,包括react、react-dom、react-router-dom 和 react-scroll。
-
设计页面结构,包含一个导航栏和多个页面内容。
-
使用 react-router-dom 来管理页面路由,使用函数式组件编写每个页面组件。
-
在导航栏中添加切换页面的链接,并使用 react-scroll 来处理点击链接时滚动到页面相应位置的功能。
-
使用 useEffect 钩子来记录每个页面滚动位置,将滚动位置存储到本地存储中。
-
在使用 react-router-dom 的路由组件中,使用 useHistory 钩子来监听路由切换事件,以便在切换页面时记录当前页面的滚动位置。
-
切换回之前的页面时,使用 useEffect 钩子和本地存储中保存的滚动位置来还原之前滚动到的位置。
以下是大致的代码实现:
import React, { useEffect, useState } from 'react';
import { BrowserRouter as Router, Switch, Route, useHistory, useLocation } from 'react-router-dom';
import { Link as ScrollLink } from 'react-scroll';
import './App.css';
function App() {
const [scrollPositions, setScrollPositions] = useState({});
useEffect(() => {
const savedScrollPositions = JSON.parse(localStorage.getItem('scrollPositions') || '{}');
setScrollPositions(savedScrollPositions);
}, []);
useEffect(() => {
localStorage.setItem('scrollPositions', JSON.stringify(scrollPositions));
}, [scrollPositions]);
return (
<Router>
<Nav />
<Switch>
<Route path="/" exact>
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
</Switch>
</Router>
);
function Nav() {
const { pathname } = useLocation();
return (
<nav>
<ScrollLink to="home" smooth>首页</ScrollLink>
<ScrollLink to="about" smooth>关于</ScrollLink>
<ScrollLink to="contact" smooth>联系我们</ScrollLink>
</nav>
);
}
function Home() {
const { pathname } = useLocation();
const history = useHistory();
useEffect(() => {
window.scrollTo(0, scrollPositions[pathname] || 0);
}, [pathname]);
useEffect(() => {
return () => {
setScrollPositions({ ...scrollPositions, [pathname]: window.pageYOffset });
};
}, [pathname]);
return (
<section id="home">
<h1>欢迎来到我们的网站</h1>
</section>
);
}
function About() {
const { pathname } = useLocation();
const history = useHistory();
useEffect(() => {
window.scrollTo(0, scrollPositions[pathname] || 0);
}, [pathname]);
useEffect(() => {
return () => {
setScrollPositions({ ...scrollPositions, [pathname]: window.pageYOffset });
};
}, [pathname]);
return (
<section id="about">
<h2>关于我们</h2>
<p>我们是一个专业的网站开发团队,致力于为客户提供优质的网站建设服务。</p>
</section>
);
}
function Contact() {
const { pathname } = useLocation();
const history = useHistory();
useEffect(() => {
window.scrollTo(0, scrollPositions[pathname] || 0);
}, [pathname]);
useEffect(() => {
return () => {
setScrollPositions({ ...scrollPositions, [pathname]: window.pageYOffset });
};
}, [pathname]);
return (
<section id="contact">
<h2>联系我们</h2>
<p>如果您有任何问题或建议,请随时与我们联系。</p>
</section>
);
}
}
export default App;
当用户在页面中滚动时,各个页面的滚动位置会记录在本地存储中。当用户切换页面时,应用会读取本地存储中的滚动位置,并滚动到上次滚动到的位置。如果用户还没有滚动页面,滚动位置默认为0。