DOM 엘리먼트에서 이벤트 처리하는 방식과 유사하지만 문법에는 차이가 있음
//DOM Elements
const handleEvent = () => {
console.log('DOM Event!!');
}
button.addEventListner('click', handleEvent)
// React Event
const handleEvent = () => {
console.log('React Event!!');
}
return (
<>
<button class="button_click" onClick={handleEvent}>Button</button>
</>
)
React Event에서는 <div> 안에 <button>이 있으면 버튼을 클릭 했을 때 디브에 이벤트가 걸리고 버튼이벤트가 실행이됩니다.
버튼을 눌러도 버튼 이벤트 보다 디브 이벤트가 먼저 발생한 이유는 비동기 처리 방식이라서 디브이벤트가 버튼이벤트 보다 위에 작성되서 디브 이벤트가 먼저 발생함
const divEvent = () => {
alert('div Event!!');
}
const buttonEvent = () => {
console.log('React Event!!');
}
return (
<>
<div class="div_click" onClick={divEvent}>
<h1>Div 영역</h1>
<button class="button_click" onClick={buttonEvent}>Button</button>
</div>
</>
)
이런 함수가 있다고 하면 <div> 안에 <button>이 있고 버튼을 클릭했을 때 비동기 처리 방식이라 버튼 이벤트 보다 디브이벤트가 위에 작성되어서 디브 이벤트가 먼저 발생하게된다.
const divEvent = () => {
alert('div Event!!');
}
const buttonEvent = (e) => {
e.stopPropagation()
console.log('React Event!!');
}
return (
<>
<div class="div_click" onClick={divEvent}>
<h1>Div 영역</h1>
<button class="button_click" onClick={buttonEvent}>Button</button>
</div>
</>
)
버튼 이벤트에 e라는 임의의 인자를 넘겨주면서 e.stopPropagation() 이라는 메서드를 실행해주면 현재 이벤트가 캡처링/버블링 단계에서 더 이상 전파되지 않도록 해줍니다.
'개인공부 > React' 카테고리의 다른 글
Styled-components (0) | 2022.10.05 |
---|---|
useState VS useRef (0) | 2022.08.05 |
#1 HOOK (useState / useEffect) (0) | 2022.07.28 |
React Style (0) | 2022.07.28 |
폼 제어 / 비제어 컴포넌트 (0) | 2022.07.28 |