wrkbrs
자바스크립트 이중 클릭 해결 본문
onClick of both child and parent triggered when child is clicked
class Sample extends React.Component { constructor(props) { super(props); this.handleChild = this.handleChild.bind(this); this.handleParent = this.handleParent.bind(this); } render() { return ( <div style={{width: '100%', height: '500px', background: 'white'}} onClick={this.handleParent}> <div style={{ width: '40px', height: '40px', margin: '0 auto', background: 'black'}} onClick={this.handleChild}> hello </div> </div> ); } handleParent(e) { console.log('parent'); } handleChild(e) { console.log('child'); } }
output when child is clicked
child parent
desire output is
child
I mean I just want to trigger only child's onClick when child is clicked.
Parent is working fine. It triggers only parent's onClick when parent is clicked. The problem I'm having is with child.
You need stop propagation inside child handler,handleChild(e) { e.stopPropagation(); console.log('child'); }
stopPropagation - Prevents further propagation of the current event in the capturing and bubbling phases.
class Sample extends React.Component { constructor(props) { super(props); this.handleChild = this.handleChild.bind(this); this.handleParent = this.handleParent.bind(this); } render() { return ( <div style={{width: '100%', height: '500px', background: 'white'}} onClick={this.handleParent}> <div style={{ width: '40px', height: '40px', margin: '0 auto', background: 'black'}} onClick={this.handleChild}> hello </div> </div> ); } handleParent(e) { console.log('parent'); } handleChild(e) { e.stopPropagation(); console.log('child'); } } ReactDOM.render(<Sample />, document.getElementById('app'));<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> <div id="app"></div>
Run code snippet
'JS' 카테고리의 다른 글
자바스크립트의 비동기 작업 처리방식 (0) | 2019.12.15 |
---|---|
자바스크립트 개발자라면 알아야 할 33가지 개념 #1 콜스택 (번역) (0) | 2019.12.15 |
[Javascript] 추출 "./"(점 슬래시)는 HTML 파일 경로 위치의 관점에서 무엇을 말합니까? (0) | 2019.12.03 |
[Javascript] 호이스팅(Hoisting) (0) | 2019.12.02 |
[JavaScript] append vs appendChild 차이점 (0) | 2019.08.12 |