简体   繁体   English

ReactJS:通过React Router dom转到HTML中的锚定链接

[英]ReactJS: Go to anchor link in HTML with react router dom

I am developing an app with patch notes where I have url's with the following structure defined with React Router: 我正在开发一个带有补丁说明的应用,其中我的网址具有通过React Router定义的以下结构:

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

I want to allow user to go to a specific part of the document if the url contains a hash part like this /updates/1#index . 如果网址包含像/updates/1#index这样的哈希部分,我想允许用户转到文档的特定部分。 Here, the #index part of the url should send the user to the div with id='index' just like normal HTML. 在这里,网址的#index部分应将用户以id='index'身份发送到div,就像普通的HTML一样。

I read about hashRouter with normal HTML for {content} but it didn't work as I expected or required: 我读了有关带有{content}普通HTML的hashRouter的信息,但是它没有按我的预期或要求运行:

<HashRouter>
  {content}
</HashRouter>

How can I achieve this? 我该如何实现?

Perhaps you could use Element#scrollIntoView() to mimic the default browser behavior of anchor link. 也许您可以使用Element#scrollIntoView()模仿锚链接的默认浏览器行为。

For instance, if <Updates /> is the component that hosts your patch note content (where anchor links are defined), then you could run this function when <Updates /> is mounted or started to achieve this: 例如,如果<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>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM