【问题标题】:How to access a href inside a <Link> tag in react-router-dom?如何访问 react-router-dom 中 <Link> 标签内的 href?
【发布时间】:2020-12-08 15:47:12
【问题描述】:

我在 react-router-dom 的 Link 标签内有一个 href 标签。该链接在我的 React.js 应用程序中运行良好。我正在尝试访问位于 Link 标记内的 href 标记,但是当我单击时,我被重定向到我的应用 Link 中指定的路由路径,而不是 href URL。

<div class="col-md-8">
    <Link id="homeLink" to="/graduate-posts">
        <img class="img-fluid" src="https://i.imgur.com/vekPedd.png" alt="Card image cap" />
        <div class="card-img-overlay">
            <div class="homeLinkTextContainer">
                <div id="homeLinkTitleContainer">
                    <p id="homeLinkTitle">Graduates</p>
                </div>
                <div class="homeLinkText" id="homeLinkTextG">
                    <p>Coming Soon! Want To <strong><a href="click.com" id="wfu"> Write For Us? </a></strong></p>
                </div>
            </div>
        </div>
    </Link>
</div>

我正在尝试访问具有 id="wfu" 的 href 标记。

当我将鼠标悬停在它上面时,我通过 Chrome 在浏览器上看到了 URL,但是当我点击它时,它没有转到我想要的 href URL,而是转到 react-router 路径。

Screenshot on browser

我尝试了 z-index,但没有奏效。任何帮助将不胜感激。

【问题讨论】:

  • 您可以将您的 href 移到 之外
  • 尝试为锚标签添加点击处理程序并编写调用event.stopPropagation()的函数

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


【解决方案1】:

尝试停止传播,以免点击事件冒泡到Link

import React from 'react';

function ExampleComponent() {
  const stopEvent = (event) => event.stopPropagation();
  wfuElement= document.getElementById("wfu");
  wfuElement.addEventListener("click", stopEvent, false);

  return (
    // your jsx above
  )
}

export default ExampleComponent;

替代解决方案

a 元素添加点击处理程序:

import React from 'react';

function ExampleComponent() {
  const stopEvent = (event) => event.stopPropagation();

  return (
    // removed everything but anchor for brevity
    <a href="click.com" id="wfu" onClick={stopEvent}> Write For Us? </a>
  )
}

export default ExampleComponent;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 2021-10-24
    • 1970-01-01
    • 2018-05-20
    • 2020-04-28
    • 2021-06-28
    • 2021-01-28
    相关资源
    最近更新 更多