【问题标题】:Prevent React Router Link from automatically generating the path of the location防止 React Router Link 自动生成位置的路径
【发布时间】:2018-10-14 02:37:09
【问题描述】:

也许我遗漏了一些东西,但我被 React Router Link 和它在“/”之外的其他位置生成的路径卡住了。简单来说,当我在家('/')时,一切都很好,但是当我在位置(例如)http://somedomain.com/posts/newest 并像这样使用 Link 组件时:

<Link to="/title-for-the-article">Link to the article</Link>

渲染后的原始 HTML a 标记看起来像这样(这不是我想要的)

<a href="/posts/title-for-the-article">Link to the article</a>

如何防止路径“/posts/”附加到每个链接组件?我只想使用通过“to”属性传递的确切路径。谢谢。

【问题讨论】:

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


    【解决方案1】:

    使用exact参数它只返回匹配url的确切路径。

    <Route exact path="/posts/title-for-the-article" component={Component} />
    
    <Link to="/posts/title-for-the-article">Link to the article</Link>
    
    // Location descriptor path to in string
    <Link to={{ pathname: '/posts/title-for-the-article' }}/>
    

    【讨论】:

    • 完美!使用位置描述符,它就像一个魅力。 :)
    猜你喜欢
    • 1970-01-01
    • 2019-06-15
    • 2017-10-02
    • 2019-06-20
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 2022-07-12
    • 2018-05-25
    相关资源
    最近更新 更多