簡體   English   中英

反應如何忽略子元素的onClick

[英]React how to ignore onClick for child element

我在父組件中有一個子組件。 我想在我點擊父級內部的任何地方時發出警報消息,除非點擊子級。

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  render() {
    return (
      <div className="parent" onClick={() => alert('x')}>
        <p>Alert clicks anywhere on this div</p>
        <div className="children">
          <button>Do not alert On this element click</button>
        </div>
        <p>Alert clicks anywhere on this div</p>
      </div>
    )
  }
}

代碼示例在這里:

http://jsfiddle.net/rgL5f9yh/

將 e.stopPropagation() 添加到子 onClick 屬性

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  render() {
    return (
      <div className="parent" onClick={() => alert('x')}>
        <p>Alert clicks anywhere on this div</p>
        <div onClick={(e) => e.stopPropagation()} className="children">
          <button>Do not alert On this element click</button>
        </div>
        <p>Alert clicks anywhere on this div</p>
      </div>
    )
  }
}

您可以防止子元素中的事件傳播,即

<button onClick={((e) => e.stopPropagation())}>Do not alert On this element click</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM