应用程序.js
import React from 'react';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import './style.css';
import Navigation from './Navigation';
import Home from './Home';
import Other from './Other';
export default function App() {
return (
<Router>
<Navigation />
<Route path="/home">
<Home />
</Route>
<Route path="/other">
<Other />
</Route>
<Route exact path="/">
<Redirect to="/home" />
</Route>
</Router>
);
}
导航.js
import React from 'react';
import { NavLink, useLocation, useHistory } from 'react-router-dom';
import * as Scroll from 'react-scroll';
export default function Navigation() {
const path = useLocation().pathname;
const location = path.split('/')[1];
const history = useHistory();
const scroller = Scroll.scroller;
const scrollToAnchor = () => {
scroller.scrollTo('anchor', {
duration: 1500,
delay: 100,
smooth: true,
offset: 50
});
};
const goToHomeAndScroll = async () => {
await closeMobile();
await history.push('/');
await scroller.scrollTo('anchor', {
duration: 1500,
delay: 100,
smooth: true,
offset: 50
});
};
const closeMobile = () => {};
return (
<div className="container">
<div className="navigation">
<NavLink to="/home" activeClassName="active">
Home
</NavLink>
<NavLink to="/other" activeClassName="active">
Other Page
</NavLink>
</div>
{location === 'home' ? (
<button onClick={scrollToAnchor}>Scroll to anchor</button>
) : (
<button onClick={goToHomeAndScroll}>
Go to Home and Scroll to anchor
</button>
)}
</div>
);
}
主页.js
import React from 'react';
import * as Scroll from 'react-scroll';
export default function Home() {
const Element = Scroll.Element;
return (
<div>
<h1>Home</h1>
<p>Welcome</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed gravida
fermentum purus egestas blandit. Nam nisl sem, feugiat hendrerit magna
non, ullamcorper pharetra nibh. Sed vestibulum nisi enim, non bibendum
lorem aliquam non. Cras turpis risus, elementum a sapien quis, dictum...
</p>
<p>
Sed volutpat, turpis vitae cursus viverra, quam tortor maximus felis,
tempus eleifend nulla metus et sapien. Curabitur vitae sodales dolor.
Phasellus a ultrices felis. Aenean efficitur nibh sit amet tortor...
</p>
<Element name="anchor">
Nam nisi nisi, aliquet at blandit et, pulvinar sit amet quam. Sed
euismod ex dui, posuere tristique purus tincidunt in. Orci varius
natoque penatibus et magnis dis parturient montes, nascetur ridiculus
mus. Vestibulum sit amet nisi commodo, pretium quam non, scelerisque...
</Element>
</div>
);
}
其他.js
import React from 'react';
export default function Other() {
return (
<>
<h1>Other page</h1>
<p>blablabla</p>
</>
);
}
演示:Stackblitz
没有 react-scroll 的结果相同:Stackblitz