单击父元素时,防止子元素成为目标

时间:2017-08-15 16:51:00

标签: javascript html css reactjs

toggleMenu(element) {
    const el = element.target
    if(hasClass(el, this.activeClass)){
        el.classList.remove(this.activeClass)
    } else {
        el.classList.add(this.activeClass)
    }
}



 <div onClick={ this.toggleMenu.bind(this) } style={this.style} className ="vis-menu-toggle">
     <div className="box" style={styles.box}>
         <div className="top" style={styles.topLine}/>
         <div className="middle" style={styles.middleLine}/>
         <div className="top" style={styles.bottomLine}/>
      </div>
  </div>

我想在点击时向父div添加一个类,但是如果它点击内部div,则目标元素不是父级,而子级接收该类。如何防止这种情况?

1 个答案:

答案 0 :(得分:3)

使用currentTarget代替target。它是当前正在调度事件的元素。

示例:

&#13;
&#13;
class Example extends React.Component {
  constructor(...args) {
    super(...args);
    this.activeClass = "active";
  }

  toggleMenu(element) {
      const el = element.currentTarget;
      el.classList.toggle(this.activeClass);
  }
  
  render() {
    return <div onClick={ this.toggleMenu.bind(this) } className="vis-menu-toggle">
       Topmost div
       <div className="box">
        Box
        <div className="top">top 1</div>
        <div className="middle">middle</div>
        <div className="top">top 2</div>
      </div>
    </div>
  }
}

ReactDOM.render(
  <Example />,
  document.getElementById("root")
);
&#13;
.active {
  border: 1px solid black;
}
&#13;
<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>
&#13;
&#13;
&#13;

旁注:

  • classListtoggle,不需要if/else(而且您忘记了el.classList在其前面)