简体   繁体   English

移除 React.js 中的监听器

[英]Remove listener in React.js

In React app I have onClick listener on Header ( handleToggle ).在 React 应用程序中,我在 Header ( handleToggle ) 上有onClick侦听器。 Header has 4 elements, the last element is Edit with own onClick listener (edit). Header 有 4 个元素,最后一个元素是带有自己的onClick侦听器的 Edit(编辑)。 How can I remove from Edit element, the listener that is applied on Header ( handleToggle ) and keep only his own listener (edit)?如何从 Edit 元素中删除应用于 Header ( handleToggle ) 的侦听器并仅保留他自己的侦听器 (edit)?

<div className="heading-panel" onClick={e => this.handleToggle(e)}>
  <h5>Name</h5>
  <h5>lastName</h5>
  <h5>Number</h5>
  <a onClick={() => this.edit()}>Edit</a>
</div>

You tell the Edit click handler to stop event propagation.您告诉编辑单击处理程序停止事件传播。

<a onClick={e => { e.stopPropagation(); return this.edit();}>Edit</a>

That does it in the anonymous handler, but you could pass the event object to this.edit and have it do it instead:这在匿名处理程序中完成,但您可以将事件对象传递给this.edit并让它执行它:

<a onClick={e => this.edit(e)}>Edit</a>

then那么

edit(e) {
    e.stopPropagation();
    // ...
}

Live Example:现场示例:

 class Example extends React.Component { edit(e) { if (this.props.stop) { e.stopPropagation(); } console.log("edit"); } handleToggle() { console.log("handleToggle"); } render() { return <div className="heading-panel" onClick={e => this.handleToggle(e)}> <h5>Name</h5> <h5>lastName</h5> <h5>Number</h5> <a onClick={e => this.edit(e)}>Edit</a> </div>; } } ReactDOM.render( <div> <div>Doesn't Stop:</div> <Example stop={false} /> <div>Stops:</div> <Example stop={true} /> </div>, document.getElementById("root") );
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

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

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