gpt4 book ai didi

javascript - ReactJS:使用react router dom转到HTML中的 anchor 链接

转载 作者:行者123 更新时间:2023-11-30 13:54:19 29 4
gpt4 key购买 nike

我正在开发一个带有补丁说明的应用程序,其中的 url 具有使用 React Router 定义的以下结构:

<Route path='/updates/:id?' render={(params) => <Updates {...params} />}></Route>

如果网址包含像 /updates/1#index 这样的哈希部分,我希望允许用户转到文档的特定部分。在这里,url 的 #index 部分应该将用户发送到带有 id='index' 的 div,就像普通 HTML 一样。

我读到了关于 {content} 的使用普通 HTML 的 hashRouter,但它没有按我的预期或要求工作:

<HashRouter>
{content}
</HashRouter>

我怎样才能实现这个目标?

最佳答案

也许你可以使用 Element#scrollIntoView() 模仿 anchor 链接的默认浏览器行为。

例如,如果 <Updates />是托管补丁说明内容的组件(其中定义了 anchor 链接),那么您可以在 <Updates /> 时运行此函数。是 mountedstarted实现这一目标:

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>
}

关于javascript - ReactJS:使用react router dom转到HTML中的 anchor 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57607378/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com