블로그를 보면서 타입스크립트를 공부하다가
e.target
과e.currentTarget
이 다르다는 것을 알고, 무엇이 어떻게 다른지 개념을 이해하고자 정리해본다.
event.currentTarget == the element to which the event handler has been attached.
The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.
핵심은 currentTarget
은 이벤트 핸들러가 부착된 것을 가리킨다는 것이다.
즉, event.target
은 부모로부터 이벤트가 위임되어 발생하는 자식의 위치, 내가 클릭한 자식 요소를 반환한다. 하지만 currentTarget
은 이벤트가 부착된 부모의 위치를 반환한다.
다음의 예제를 통해 살펴보자. button
태그에 onClick
이벤트가 걸려있다. 그리고 하위에는 span
태그가 있다.
<li>
<button onClick={onLogin}>
<span>Button</span>
</button>
</li>
그리고 버튼을 클릭 했을 때 어떤 것이 반환되는지 확인하기 위해 콘솔을 찍어두었다.
const onLogin = (event) => {
console.log(event.target);
console.log(event.currentTarget);
};
실행 결과는 다음과 같다.
event.target
은 자식 요소인 span
을 리턴하고, event.currentTarget
은 부모 요소인 button
을 반환하는 것을 알 수 있다.