与this angular question非常相似:在使用react-router时,如何使用锚链接进行页面内导航?
换句话说,当我使用react-router时,我如何实现下面的普通HTML?
<a href="#faq-1">Question 1</a>
<a href="#faq-2">Question 2</a>
<a href="#faq-3">Question 3</a>
<h3 id="faq-1">Question 1</h3>
<h3 id="faq-2">Question 2</h3>
<h3 id="fa1-3">Question 3</h3>目前,我拦截这些链接上的点击,并滚动到锚点位置。这并不令人满意,因为这意味着不可能直接链接到页面的某个部分。
发布于 2015-04-05 19:03:29
锚链的问题在于,react-router的默认设置是使用URL中的散列来维护状态。幸运的是,您可以根据Location documentation将默认行为替换为其他行为。在您的例子中,您可能希望使用HistoryLocation对象来尝试“清理URL”,这意味着react-router不会使用URL散列。像这样试一下:
Router.run(routes, Router.HistoryLocation, function (Handler) {
React.render(<Handler/>, document.body);
});发布于 2017-08-20 07:43:40
React Router Hash Link为我工作。易于安装和实施:
$ npm install --save react-router-hash-link在您的component.js中,将其作为链接导入:
import { HashLink as Link } from 'react-router-hash-link';使用<Link>,而不是使用锚<a>:
<Link to="#faq-1>Question 1</Link>
<Link to="#faq-2>Question 2</Link>
<Link to="#faq-3>Question 3</Link>注意:我使用了HashRouter而不是Router
发布于 2019-12-02 01:41:12
import { Link } from 'react-router-dom'
链接使用
<Link to='/homepage#faq-1'>Question 1</Link>
然后在目标React组件(主页)中插入以下代码:
useEffect(() => {
const hash = props.history.location.hash
// Check if there is a hash and if an element with that id exists
const el = hash && document.getElementById(hash.substr(1))
if (el) {
el.scrollIntoView({behavior: "smooth"})
}
}, [props.history.location.hash]) // Fires every time hash changeshttps://stackoverflow.com/questions/28893855
复制相似问题