【问题标题】:ReactJS: Go to anchor link in HTML with react router domReactJS:使用反应路由器 dom 转到 HTML 中的锚链接
【发布时间】:2019-08-22 10:33:27
【问题描述】:

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

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

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

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

<HashRouter>
  {content}
</HashRouter>

我怎样才能做到这一点?

【问题讨论】:

  • 您想滚动到指定id的元素吗?
  • @DacreDenny 是的,我希望它像普通 HTML 一样工作,但使用 React 路由器 dom

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

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

例如,如果&lt;Updates /&gt; 是托管您的补丁说明内容的组件(其中定义了锚链接),那么您可以在&lt;Updates /&gt;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>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-02
    • 2021-09-11
    • 2018-02-16
    • 2022-01-21
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    相关资源
    最近更新 更多