简体   繁体   English

反应<a>标签和按钮onClick传播</a>

[英]React <a> tag and button onClick propagation

I want to create a React component with a render method that has an <a> tag that wraps an entire "box", if you will, which redirects to another page when clicked. 我想创建一个带有render方法的React组件,该方法具有一个包含整个“box”的<a>标签,如果愿意,它会在单击时重定向到另一个页面。 Within said box there is a <button> that can be clicked that activates an event that changes state. 在所述框内,有一个<button>可以点击,激活一个改变状态的事件。 What I want to be able to do is click the <button> and trigger the event without the redirect from the <a> tag occurring. 我希望能够做的是单击<button>并触发事件,而不会发生<a>标签的重定向。

Tried some ideas with stopPropagation() but no luck :/ I don't want to move the button outside of the <a> tag either so not sure where to go from here. 用stopPropagation()尝试了一些想法,但没有运气:/我不想移动<a>标签之外的按钮,所以不知道从哪里开始。

It seems like it should be something simple but I just can't figure it out. 它似乎应该是简单的东西,但我无法弄明白。 Thanks! 谢谢!

the render method looks like this: render方法如下所示:

render(){
 return(
  <div>
   <a href="http://www.google.com"> 
    <div className="box">

     <h2 className="title">Random Title</h2>

     <button onClick={this.handleClick}> Like </button>

    </div>  
   </a>
  </div> 
 )
}

handleClick() would look something like this: handleClick()看起来像这样:

handleClick = () => {
  if (this.state.liked) {
  console.log("disliking")
} else {
  console.log("liking")
}

this.setState({ liked: !this.state.liked})
}

What you are wanting to do does not seem possible. 你想做什么似乎不可能。 Once the user clicks on the <a> enclosed content they will be redirected to the linked content, in your case: http://www.google.com If you want to execute your function then follow the link you must remove the <a> tag and put window.location = "http://www.google.com"; 一旦用户点击<a>随附的内容,他们将被重定向到链接的内容,在您的情况下: http//www.google.com如果您想执行您的功能,请按照您必须删除<a>的链接<a>标记并放置window.location = "http://www.google.com"; at the end of your function. 在你的功能结束时。

you can achieve this with a simple trick. 你可以通过简单的技巧实现这一目标。 see what I did - 看看我做了什么 -

  1. replace the anchor with a div and place a click handler 用div替换锚点并放置一个单击处理程序
  2. add a flag (clicked) with in the component and ignore in div click handler if it's a button click 在组件中添加一个标记(单击),如果是单击按钮,则在div单击处理程序中忽略
  3. reset the flag 重置标志

update - check out this js fiddle : https://jsfiddle.net/rabinarayanb/pvx2n3x3/ 更新 - 看看这个js小提琴: https //jsfiddle.net/rabinarayanb/pvx2n3x3/

note - I have used es5 syntax. 注意 - 我使用了es5语法。 you can convert to es6 你可以转换为es6

(function() {   
    var BoxSetup = React.createClass({


        clicked : "",

        getInitialState : function () {
            return { clickCount : 0};
        },

        handleDivClick : function (event) {
            if (this.clicked !== "Button") {
                window.location.href = "http://www.google.com";
            }

            // reset
            this.clicked = "";
        },

        handleButtonClick : function (event) {
           this.clicked = "Button"
           this.setState({
                clickCount : ++this.state.clickCount
           });
        },

        render : function () {

            return (
            <div>
                <div onClick={this.handleDivClick} style={ { }}>
                    <div style={ { width : "100px", height : "100px", border : "1px solid red" } }>
                        <h2 className="title">{ this.state.clickCount }</h2>
                        <button onClick={this.handleButtonClick}> Like </button>
                    </div>
                </div>
            </div> 
            );
        }
    });

    var element = React.createElement(BoxSetup, { title : "Hello" });

    ReactDOM.render(element, document.getElementById("app"));    
})();

One way this can be done is by setting a reference to the anchor element, then using the button elements onMouseEnter and onMouseLeave to programatically change the anchor elements href property whenever the user moves the mouse over the Like button. 可以这样做的一种方法是通过设置对anchor元素的引用,然后使用onMouseEnter和onMouseLeave上的按钮元素以编程方式更改锚元素href属性,只要用户将鼠标移到Like按钮上。

class Test extends React.Component {

  constructor(props){
    super(props)
    this.state={ likes:0 }
    this.anchorElement=null;
  }

  enter = () => { this.anchorElement.href='javascript:;'; }
  leave = () => { this.anchorElement.href='http://www.google.com'; }
  handleClick = () => { this.setState({ likes: ++this.state.likes}); }

  render() {
    return (
      <div>
        <div>{'Likes:'+this.state.likes}</div>
        <a href="http://www.google.com" ref={(el) => { if (el) { this.anchorElement = el; } }}>
          <div>
            <h2 className="title">Random Title</h2>
            <button onClick={this.handleClick} onMouseEnter={this.enter} onMouseLeave={this.leave}> Like </button>
          </div>
        </a>
      </div>
    );
  }
}

See it in action: Working fiddle 看到它在行动: 工作小提琴

In the fiddle you will note the link is activating, but is not going anywhere because it is effectively "turned off" while the button is under the mouse. 在小提琴中,你会注意到链接正在激活,但是不会去任何地方,因为当按钮位于鼠标下时它会被有效地“关闭”。 If you want to get rid of the appearance of activation on the link, a little more manipulation of the anchor element is needed, or simply set the a:active css property to the same color as the base/active color. 如果您想要消除链接上激活的外观,则需要对锚元素进行更多操作,或者只需将a:active css属性设置为与基本/活动颜色相同的颜色。

Personally, I would avoid the scenario if possible, but that's just good advice, something that more folks around here should learn is not the same thing as an answer. 就个人而言,如果可能的话,我会避免这种情况,但这只是一个很好的建议,这里的更多人应该学习的东西与答案不同。

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

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