S. *_*enk 12 javascript reactjs react-router
当用户通过锚链接导航到页面时,我希望页面向下滚动到我的锚标签.
我正在使用react-router 4,我已经定义了如下内容:
导航栏:
export default (props) => {
const {
updateModal,
updateRoute,
} = props
return(
<Navbar fluid collapseOnSelect>
<Nav>
<NavDropdown eventKey="4" title="Solutions" id="nav-dropdown" noCaret>
<MenuItem eventKey="4.1">
<Link to='/solution#ipos'>TESTING ANCHOR</Link>
</MenuItem>
...
Run Code Online (Sandbox Code Playgroud)
一些路线:
export default class extends Component {
constructor() {
super()
this.state = {
isLoading: true
}
}
render() {
return (
<Grid className='solutions' fluid>
<Row className='someClass'>
<div>
<h2><a href='ipos' id='ipos'>Ipos morna santos paros</a></h2>
...
Run Code Online (Sandbox Code Playgroud)
当我点击navebar中的锚链接时,我可以在url和我的redux商店中看到哈希锚标记,它确实导航到新路由,但它不会向下滚动到标记本身.
是由我来创建滚动功能还是它应该如何正常工作?
小智 20
要向下滚动到锚标签,您需要安装React Router Hash Link,其中包括:
npm install --save react-router-hash-link
Run Code Online (Sandbox Code Playgroud)
然后导入哈希链接:
import { HashLink as Link } from 'react-router-hash-link';
Run Code Online (Sandbox Code Playgroud)
然后使用Hash Link,例如:
<Link to="/pathLink#yourAnchorTag">Your link text</Link>
Run Code Online (Sandbox Code Playgroud)
并在目标组件,例如:
<div id= "yourAnchorTag">
<p>Linked to here<p>
</div>
Run Code Online (Sandbox Code Playgroud)
Akh*_*l P 13
这是反应路由器的一个已知问题.(https://github.com/ReactTraining/react-router/issues/394#issuecomment-220221604)
还有一个解决方案.https://www.npmjs.com/package/react-router-hash-link这个包解决了这个问题.
你必须Hash Link在Link下面使用它.
import { HashLink as Link } from 'react-router-hash-link';
如果您只有几个可预测的锚链接,实现正常行为的最简单方法是手动删除scrollIntoView()元素,如果您在Window.location.href.
class Page extends react.Component {
componentDidMount() {
if (this.$ref && location.href.includes('#my-ref')) {
this.$ref.scrollIntoView({
// optional params
behavior: 'smooth',
block: 'start',
inline: 'center',
});
}
}
render() {
return (
// This is the div you want to scroll to
<div ref={ref => {
this.$ref = ref;
}}>
Other content
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
检查Element.scrollIntoView()和React refs。
小智 6
您可以将对象传递给 Link,如下所示
<Link
to={{
pathname: "/courses",
search: "?sort=name",
hash: "#the-hash",
state: { fromDashboard: true }
}}
/>
Run Code Online (Sandbox Code Playgroud)
参考号 https://reacttraining.com/react-router/web/api/Link
| 归档时间: |
|
| 查看次数: |
24860 次 |
| 最近记录: |