调用两个函数

时间:2017-09-15 06:07:19

标签: javascript reactjs stoppropagation

我有一个div和顶部,那是另一个图像。我已经为我的div和图像提供了onClick方法。我想在点击div顶部的图像时停止为下面的div提供的onClick方法。

我能够使用e.stopPropagation();停止它。但后来我不得不在图像的onClick上添加另一种方法。添加后,我的e.stopPropagation();停止了工作。我该如何解决这个问题。

代码有效时

enlarge() {

        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();

        this.setState({
            showFullImage: true,
        });

    }


<div onClick={() => this.handleClick(content.post_poll_content_id)}>
       <div className="float_right full_div" onClick={this.enlarge}>
          <img src={extend} className="extend_icon" />
      </div>
</div>

代码停止工作时

enlarge() {

        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();

        this.setState({
            showFullImage: true,
        });


    }

    passImage(img){

        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();

        this.setState({

            img:img

        })

    }

<div onClick={() => this.handleClick(content.post_poll_content_id)}>
    <div className="float_right full_div" onClick={()=>{this.enlarge();this.passImage(content.content);}}>
         <img src={extend} className="extend_icon" />
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

我猜你误解了stopPropagation()

  1. 如果要停止将代码从enlarge()传播到passImage(),则需要实现自定义逻辑。让我们说enlarge()设置一个passImage()在执行前验证的变量。

  2. 如果你真的打算停止从内部div的onClick执行执行到外部div,它对我有效。以下是您可以测试的代码快照。

  3. ``

    <html>
       <head>
       <script>
         function click_innermostdiv1(){
                event.stopPropagation();
                alert("click_innermostdiv1 : innermostdiv was clicked.");
         }
    
         function click_innermostdiv2(){
                event.stopPropagation();
                alert("click_innermostdiv2 : innermostdiv was clicked.");
         }
    
         function click_outermostdiv(){
                alert("The outermostdiv element was clicked.");
         }
    
         function click_middlediv(){
                alert("The middlediv element was clicked.");
         }
       </script>
       </head>
       <body>
          <div style="height:100px;width:500px;padding:10px;border:1px solid blue;background-color:lightblue;" onClick="click_outermostdiv();">
             This is outermost div element.
             <div style="background-color:pink" onClick="click_middlediv();">
                This is middle div element. <br>
                <div style="background-color:orange" onClick="click_innermostdiv1();click_innermostdiv2();">
                      This is a innermost div element.
                </div>
             </div>
          </div>
       </body>
    </html>
    

    ``

    1. [调试提示]当stopPropagation()失败时,我可以想到一些可能的情况:

      • 当方法名称不正确时:检查控制台是否记录了类似的内容。
      • 方法未成功完成时。通过打印日志语句检查执行是否超出stopPropagation()