【问题标题】:React Router browserHistory push and anchorsReact Router 浏览器历史推送和锚点
【发布时间】:2018-05-16 18:17:51
【问题描述】:

使用 React Router 4 中的 browserHistory 以编程方式导航到锚点时:

import { withRouter } from 'react-router-dom'
...
props.history.push('#blah')

我可以看到地址栏中的哈希值发生了变化,但页面没有滚动到相关的锚点。我已经用标准<a href="#blah">Blah</a> 对其进行了检查,并且效果很好。知道我做错了什么吗?谢谢:)

更新
刚刚检查过,<Link to="#blah">Blah</Link> 也不起作用......我假设反应 Links 也使用历史对象工作?

【问题讨论】:

  • 我正在使用浏览器路由器,这就是我谈论浏览器历史的原因。正如您从我上面的帖子中看到的那样,我已经完全尝试了您建议的代码行(this 除外,因为我正在使用功能组件)
  • @Aaqib 不正确。这是完全不相关的问题。推路径工作正常,推哈希不行。

标签: reactjs react-router anchor browser-history react-router-v4


【解决方案1】:

经过一番调查,我决定添加一个函数来处理 componentDidUpdate 生命周期事件:

componentDidUpdate: props => {
  const selected = props.history.location.hash
  if(selected && selected.length > 0) {
    const elem = document.querySelector(selected)
    elem && elem.scrollIntoView()
  }
}

这很好地解决了这个问题:)

【讨论】:

  • 这行得通,我只需要使用querySelector() 而不是getElementById(),因为selected 包含英镑符号#。 getElementById 只需要没有 # 的 ID。 querySelector 工作正常。
猜你喜欢
  • 2017-12-29
  • 2017-03-17
  • 2017-08-17
  • 2018-12-26
  • 1970-01-01
  • 2019-01-03
  • 2018-07-20
  • 2016-12-05
  • 2022-10-12
相关资源
最近更新 更多