首页 > 解决方案 > 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>

我怎样才能做到这一点?

标签: javascriptreactjsreact-routerreact-router-dom

解决方案


也许您可以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>
}

推荐阅读