我在内部使用react-boilerplate (3.4.0)和react-router进行路由。
我尝试使用
发布于 2017-05-23 23:19:40
这可能会晚一点,但您可以做的是将此代码添加到您的组件中:
import ReactDOM from 'react-dom';
... some more codez...
componentDidUpdate() {
const anchor = this.props.location.hash.replace('#', '');
if (anchor) {
const domElement = ReactDOM.findDOMNode(this.refs[hash]);
if (domElement) {
domElement.scrollIntoView();
}
}
}
然后在要导航到的实际元素上,需要添加ref
属性,如下所示:
<h1 ref="my-anchor">Hello World</h1>
link元素看起来就像一个普通的link:
<a href="/about#my-anchor>Go To Anchor</a>
或者使用react-router:
<Link key="my-anchor" to="/about#my-anchor">Go To Anchor</Link>
这适用于react-router 2.6.1 -目前不确定更新的版本。
希望这能有所帮助!
发布于 2017-12-20 04:18:48
改进了上面的答案:
componentDidMount() {
const anchor = this.props.location.hash;
if (anchor) {
const domElement = document.querySelector(anchor);
if (domElement) {
domElement.scrollIntoView();
}
}
}
发布于 2018-08-03 05:21:04
我强烈推荐使用Rafael Pedicini提供的名为react-router-hash-link的包。
活生生的例子there。它工作得很好,代码也很干净。
https://stackoverflow.com/questions/41739847
复制相似问题