【问题标题】:React-Router-Dom Hash RouterReact-Router-Dom 哈希路由器
【发布时间】:2019-03-26 00:34:50
【问题描述】:

我遇到了一些奇怪的事情,我不确定为什么会这样。我正在使用来自 React-Router-Dom 的 HashRouter,因为我试图在 Github Pages 上托管我的投资组合。当我链接到新页面时,新页面加载完美,但似乎将我带到新页面的底部,而不是顶部。有谁知道为什么会发生这种情况?

app.js:

  <HashRouter>
        <div>
        <Navigation />
        <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/About" component={About} />
        <Route path="/MyHumber" component={MyHumber} />
        <Route path="/Foragr" component={Foragr} />
        <Route path="/TheWatchlist" component={TheWatchlist} />
        </Switch>
        </div>
  </HashRouter>

链接:

  <Col lg={6}>
    <h1 className="project-title">{this.state.title}</h1>
    <p>{this.state.description}</p>
      <Link to={this.state.path}>
        <Button>View Project</Button>
      </Link>
   </Col>

【问题讨论】:

  • 据我了解,问题是在加载新页面时,它会立即滚动到底部?导航后地址栏中的 url 是什么样的?页面底部是否有 som 元素以某种方式吸引焦点?有没有自动对焦形式之类的?
  • 它不会滚动,但是当我单击链接时,会显示新页面,但它会自动显示在页面底部。例如,网址显示“localhost:3000/#/MyHumber”。没有表格或任何东西。
  • 我明白了。如果需要保留上一页的滚动位置,文档中的此页面可能会有所帮助:reacttraining.com/react-router/web/guides/scroll-restoration。否则,我看不出您粘贴的代码有什么问题。您是否能够在代码沙箱中重现问题?

标签: reactjs react-router-dom


【解决方案1】:

试试:

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

history.listen(_ => {
  window.scrollTo(0, 0)  
});

在HashRouter标签中:

    <HashRouter history={history}>

    </HashRouter>

这对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2019-05-30
    • 2018-06-08
    • 2018-06-04
    • 1970-01-01
    • 2022-10-16
    • 2019-06-15
    相关资源
    最近更新 更多