React的stopPropagation不适用于父事件处理程序

时间:2019-05-31 08:34:31

标签: reactjs event-handling stoppropagation

我尝试了Internet上提供的解决方案,但是没有运气。这是codepen link。代码是这样的:

//JSX:
    <div className="drawer-component" onClick={this.closeDrawer}>
      <div className="drawer-opener">
        <button onClick={this.toggleDrawer}>Toggle</button>
      </div>
      {this.state.isOpen && <div class="drawer">Hello I am a drawer. Cliking on me should not close myself.</div>}
    </div>


// Event Handlers:

toggleDrawer(e) {
  e.stopPropagation();
  this.setState((state, props) => {
      return {isOpen: !state.isOpen};
  })
}

closeDrawer(e) {
  e.stopPropagation();
  this.setState((state, props) => {
      return {isOpen: false};
  })
}

不知道我在做什么错,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

该行为与编写的代码匹配。 您将文本放在div(class ='drawer')中,没有任何单击处理程序,因此将执行父级的单击处理程序(div class ='drawer-component'),在这种情况下,它将设置状态变量isOpen虚假并关闭抽屉。此操作中的e.stopPropagation()不会影响任何内容,因为该div没有其他带有单击处理程序的父对象,该事件可能传播到该处理程序。

如果您希望在不关闭抽屉的情况下单击文本,请为div添加一个单击处理程序(带有class ='drawer'),以防止传播。

    closeDrawer(e) {
      // e.stopPropagation();  This isn't required as there's nowhere further the event can get propagated
      this.setState((state, props) => {
          return {isOpen: false};
      })
    }

   // Prevent click handler of parent being called and closing the drawer
   preventClosingOnTextClick(e) {
      e.stopPropagation();
    }

    render() {
      return (
        <div className="drawer-component" onClick={this.closeDrawer}>
          <div className="drawer-opener">
            <button onClick={this.toggleDrawer}>Toggle</button>
          </div>
          {
           this.state.isOpen && 
             <div class="drawer" 
              onClick={this.preventClosingOnTextClick}> // This prevents the closing
                 Hello I am a drawer. Cliking on me should not close myself.
             </div>
          }
        </div>
      );
    }
  };

);