React prevent event bubbling in nested components on click

前端 未结 8 1542
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 02:41

Here\'s a basic component. Both the

    and
  • have onClick functions. I want only the onClick on the
  • to fir
8条回答
  •  旧时难觅i
    2020-11-27 03:14

    I had issues getting event.stopPropagation() working. If you do too, try moving it to the top of your click handler function, that was what I needed to do to stop the event from bubbling. Example function:

      toggleFilter(e) {
        e.stopPropagation(); // If moved to the end of the function, will not work
        let target = e.target;
        let i = 10; // Sanity breaker
    
        while(true) {
          if (--i === 0) { return; }
          if (target.classList.contains("filter")) {
            target.classList.toggle("active");
            break;
          }
          target = target.parentNode;
        }
      }
    

提交回复
热议问题