在react-router 4中使用锚标签

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)

  • 2022 年 4 月报道,(经过一些研究)这仍然是最好的方法。 (11认同)
  • 2020 年 2 月报道,这仍然是最好的方法(遗憾的是) (10认同)
  • 很难相信,在此软件包之外还没有一种更普遍的做法。似乎真的很奇怪。 (6认同)
  • 实际上我什至无法让它按预期运行。这个框架有时可能会让人大失所望。我有一个具有永远不会改变的静态 ID 的元素,我想做的就是添加一个 a[href="#myAnchor"] 并滚动到它。如果没有至少 20 行代码,这似乎是不可能的。 (3认同)
  • 对我来说也很有趣的是,这个答案是唯一提供如何编写您要链接的内容的示例的答案。谢谢@阿德里安 (2认同)

Akh*_*l P 13

这是反应路由器的一个已知问题.(https://github.com/ReactTraining/react-router/issues/394#issuecomment-220221604)

还有一个解决方案.https://www.npmjs.com/package/react-router-hash-link这个包解决了这个问题.

你必须Hash LinkLink下面使用它.

import { HashLink as Link } from 'react-router-hash-link';

  • 然而值得注意的是,在这种情况下,只需使用标准的“&lt;a&gt;”链接就可以轻松避免这种情况。React-Router `&lt;Link&gt;` 不是必需的,因为如果您在同一页面中导航,则不需要在此处进行组件操作。因此,标准的“&lt;a&gt;”链接可以被认为是最佳解决方案,它不需要安装另一个包等。但是,如果您需要导航到另一个“页面”上的哈希链接,那么是的,这个包将是解决方案。 (4认同)

Fil*_*ppo 8

如果您只有几个可预测的锚链接,实现正常行为的最简单方法是手动删除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