【问题标题】:How can I scroll to a page when doing React Router history push in my case在我的情况下进行 React Router 历史推送时如何滚动到页面
【发布时间】:2020-11-18 18:07:23
【问题描述】:

我学习了一些 React-router-dom,它有点工作,但是因为我有三个 Components 一个接一个,就像一个长页面。然后当我点击顶部菜单中的about 按钮时;

<Button variant="primary" onClick={() => history.push('/articles')}>
        Articles
</Button>
<Button variant="primary" onClick={() => history.push('/stories')}>
        Stories
</Button>
<Button variant="primary" onClick={() => history.push('/about')}>
        About
</Button>

/about 页面已呈现但未滚动到,因为它的页码为 3。有什么方法可以自动滚动到该页面吗?

我的菜单不是固定的,但是每当用户向上滚动菜单时,当用户向下滚动菜单时,菜单就会消失,不会阻止内容。

看起来这三个组件组成了一个长页面

react router 或useHistory 中可能有内置的东西,还是我必须想办法让组件知道它们是从主菜单中召唤出来的?然后自己计算如何滚动变得可见。

我对 React Redux 知之甚少,我想我可以从菜单按钮调度和操作,mapStateToProp 监听组件中的操作,然后滚动可见。感觉就像一个糟糕的黑客不知道。

【问题讨论】:

  • 我已经用其他解决方案更新了我的答案,请注意,如果它是一个类组件,您需要在 Button 元素内编写 this.onAboutPageClick 。而且 scrollIntoView 有很多选项来管理滚动行为

标签: reactjs scroll react-router-dom


【解决方案1】:

不确定这是否可行,或者是否是一致/最佳的解决方案,但就这里没有其他答案而言,您可以尝试使用它

  const onAboutPageClick = () =>{
    const aboutPageNode = document.getElementById('aboutPage')

    aboutPageNode.scrollIntoView({behavior: "smooth"});
    history.push('/about')
}


<Button variant="primary" onClick={() => history.push('/articles')}>
  Articles
</Button>
<Button variant="primary" onClick={() => history.push('/stories')}>
Stories
</Button>
<Button variant="primary" onClick={onAboutPageClick}>
    About
</Button>


..... some other html code

<div id="aboutPage"> Here is about page </div>

【讨论】:

  • 当我尝试此操作并单击 Button 时会发生什么情况,即应用程序完全重新加载,就像我按下 F5 刷新一样。很奇怪! .我删除了onClick={() =&gt; history.push..
  • 还有一件事
  • 如果这一切都在一个页面上并且您没有通过其他功能跟踪位置来启动某些操作,那么您甚至不需要 history.push('/about') 。不太清楚,我不是 react-router 大专家
  • @TordLarsen 虽然这个答案'是正确的,但我建议使用Refs 而不是 document.getElemetById 如这里讨论的refs vs getelementbyid 和是的,你不'除非您希望在其他页面上这样做,否则不需要 React-router-dom 这样做。
  • @TordLarsen 是的,看看这个sandbox
【解决方案2】:

在上面 Dmitriy Sakhno 所说的答案中,我认为它给出了一个错误,因为它找不到它,因为页面尚未呈现 所以我使用了 setTimeout 并且成功了。

const onAboutPageClick = () => {
    history.push('/about')
    setTimeout(() => {
      const aboutPageNode = document.getElementById('aboutPage');
      aboutPageNode.scrollIntoView({behavior: "smooth"});
    }, 0);
}

【讨论】:

    猜你喜欢
    • 2020-01-31
    • 2020-10-16
    • 2017-07-30
    • 2022-07-18
    • 2015-02-14
    相关资源
    最近更新 更多