【问题标题】:Not able to attach click event to an Anchor tag inside a react component无法将点击事件附加到反应组件内的锚标记
【发布时间】:2020-02-17 23:44:49
【问题描述】:

下面是我的代码 组件A.js

组件内部的return语句

 return (
       ......

        <a id="MytoolTip" ......  

       <ComponentB
          content={
            `
            <div class="share_cart_tt">
                  <a 
                  data-automation-id="..."
                  class="callFunction" 
                   > Invite </a>
            </div>
           `
          }
          target={'MytoolTip'}
          closeButton
       />

);

ComponentB.js(这是一个工具提示,当用户单击锚标记 MytoolTip 时将显示)

.....

class ComponentB extends Component {
  launchModal() {
    console.log("hey its fine");
  }
     ...
      renderContent = () => {
          document.getElementsByClassName('callFunction').
          addEventListener('click', this.launchModal);
      **I am trying to bind click event here but its not working out**
     }

}

我是初学者,我尝试了不同的方法来绑定点击事件,但没有任何结果..需要帮助。 当用户单击工具提示内的锚标记时,应打印带有类 .callFunction 的 console.log。

请注意,我正在尝试将 onClick 事件添加到锚标记,这只是 ComponentA 中的静态内容,并且将通过在 ComponentB 中的 prop.content 中获取静态内容来创建工具提示

【问题讨论】:

    标签: javascript reactjs dom-events


    【解决方案1】:

    React 组件有synthetic event listeners。您需要做的就是将onClick 属性添加到元素。所以你的看起来像这样:

    return (
           ......
    
            <a id="MytoolTip" ......  
    
           <ComponentB
              content={
                `
                <div class="share_cart_tt">
                      <a 
                      data-automation-id="..."
                      onClick={FunctionToBeCalledWhenClicked}
                      class="callFunction" 
                       > Invite </a>
                </div>
               `
              }
              target={'MytoolTip'}
              closeButton
           />
    
    );
    

    【讨论】:

    • 我认为你需要 preventDefault 来覆盖导航的默认行为
    • 是的,OP 需要在被调用的函数中 preventDefault()。我没有将其添加到我的答案中,因为仅询问了有关如何添加事件侦听器的问题,而不是触发事件后如何处理事件。
    • @technicallynick .. 我已经尝试过这个 onClick one。它给出了错误'launchShareCartModal未定义'
    • 我必须查看你的组件的其余部分(不仅仅是渲染)来帮助你。也许是this.launchShareCartModal
    猜你喜欢
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 2013-07-14
    相关资源
    最近更新 更多