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



我尝试了互联网上提供的解决方案,但没有运气。这是代码笔链接。代码如下所示:

//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};
  })
}

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

行为与编写的代码匹配。您的文本位于没有任何点击处理程序的div(class='drawer'( 中,因此父级的点击处理程序(div class='drawer-component'(被执行,在这种情况下,它将您的状态变量 is Open 设置为 false 并关闭抽屉。其中的 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>
      );
    }
  };
);

相关内容

  • 没有找到相关文章

最新更新