javascript - ReactJS:使用反应路由器 dom 转到 HTML 中的锚链接
问题描述
我正在开发一个带有补丁说明的应用程序,其中我的 url 具有使用 React Router 定义的以下结构:
<Route path='/updates/:id?' render={(params) => <Updates {...params} />}></Route>
如果 url 包含这样的哈希部分,我想允许用户转到文档的特定部分/updates/1#index
。在这里,url 的一部分应该像普通的 HTML 一样#index
将用户发送到 div 。id='index'
我阅读了带有普通 HTML 的 hashRouter 的信息,{content}
但它没有按我的预期或要求工作:
<HashRouter>
{content}
</HashRouter>
我怎样才能做到这一点?
解决方案
也许您可以Element#scrollIntoView()
用来模仿锚链接的默认浏览器行为。
例如,如果<Updates />
是托管您的补丁说明内容的组件(其中定义了锚链接),那么您可以在挂载或开始<Updates />
时运行此函数来实现此目的:
function scrollToHash() {
/* Obtain hash from current location (and trim off leading #) */
const id = window.location.hash.substr(1);
if(id) {
/* Find matching element by id */
const anchor = document.getElementById(id);
if(anchor) {
/* Scroll to that element if present */
anchor.scrollIntoView();
}
}
}
/* Usage example */
function Updates() {
React.useEffect(() => {
scrollToHash();
},[]);
/* Render patch content that contains anchors */
return <div> ... </div>
}
推荐阅读
- apache-spark - Spark Structured Streaming foreachBatch 和 UPSERT(合并):坚持还是不坚持?
- django - 如何在 Django Rest Framework 中使用自定义属性名称序列化 JSON
- javascript - 如何让 JS 函数从 HTML 按钮返回到标题?
- c++ - 从 txt 文件中的一行生成 QStringList
- javascript - 上边距或任何边距移动所有按钮而不是一个。请记住,我无法使用 CSS,因为我使用的是 webstorm 解释器
- html - CKEditor SetData() 显示原始 HTML
- laravel - 在 null 上调用成员函数 store() 我检查了名称
- scala - 期货/并行代码的有用堆栈跟踪
- php - file_get_contents 未捕获所需数据
- mysql - 如何获得包含匹配和不匹配记录的 mysql 结果集