wrkbrs

자바스크립트 이중 클릭 해결 본문

JS

자바스크립트 이중 클릭 해결

zcarc 2020. 3. 12. 07:23

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

Expand snippet

 

 

https://stackoverflow.com/questions/39470071/onclick-of-both-child-and-parent-triggered-when-child-is-clicked