简体   繁体   English

在标签内反应 JS onClick 事件

[英]React JS onClick event inside a tag

I have this piece of code that is a tag that has a onClick event inside.我有一段代码,它是一个标签,里面有一个onClick事件。 My problem is that when I click on the div in the browser the href is triggered and I am taking to the other site.我的问题是,当我点击浏览器中的 div 时,href 被触发,我正在访问另一个站点。 Is there a way to make sure so only the onClick is triggered when clicking on chnageOrder有没有办法确保is triggered when clicking on chnageOrder is triggered when clicking onis triggered when clicking on onClick onClick` and the link works when clicking the rest of the a tag? onClick` 并且在单击 a 标记的其余部分时链接有效?

  <div key={idx.toString()}>
    <a className="stage-container" href={stageUrl}>
      <h3>{stage.title}</h3>
      <div className="arrow-container">
        <div
          className=""
          onClick={() =>  
            changeOrder(stage.id, stage.title, stage.order - 1)
          }
        >
          <i className="fa fa-caret-up" />
        </div>
        <div
          onClick={() =>
            changeOrder(stage.id, stage.title, stage.order + 1)
          }
        >
          <i className="fa fa-caret-down" />
        </div>
      </div>
    </a>
    <div className="substages-container">
      {sortSubstages.map((substage, index) => (
        <SubstageItem 
          className="substage-container" 
          key={index.toString()} 
          substage={substage} 
          reload={reload} 
        />
      ))}
    </div>
  </div >

Try:尝试:

 onClick={(e) => { e.preventDefault(); e.stopPropagation(); changeOrder(stage.id, stage.title, stage.order - 1); } }

You can use PreventDefault to avoid triggering the href link.您可以使用 preventDefault 来避免触发 href 链接。 You can have a look at https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault你可以看看https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

HandleChangeOrder = (event,stageid, stagetitle, stageorder) =>{
event.PreventDefault();
//your changeOrder method instructions
}

//Call
<div className="" onClick={() => changeOrder(this.HandleChangeOrder)}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM