ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [자바스크립트] target 과 currentTarget 차이
    javascript 2021. 6. 11. 11:32
    반응형
    const handleChange = (e: React.FormEvent<HTMLInputElement>)=>{
        setInput({
          ...input,
          [e.target.name]:e.target.value
        })
      }

    이벤트에 타입을 걸어주는데 검색해서 붙여넣었더니 에러가 발생했다.

     

    Property 'value' does not exist on type 'EventTarget'

     

    그래서 다시 검색해보니까

    onChange = (e: React.FormEvent<HTMLInputElement>) => {
        const newValue = e.currentTarget.value;
    }
    
    onChange = (e: React.ChangeEvent<HTMLInputElement>)=> {
       const newValue = e.target.value;
    }

    이벤트의 타겟에 대상을 가져오는데 두가지 경우가 있다라는 걸 다시한번 보게 됬다. 본적은 있었는데 딱히 생각 안해봤던 부분이였는데

    tartget 과 currentTarget 이 뭐가 다른 건지 한번 찾아보자

    mdn 을 보면

    인터페이스  currentTarget읽기 전용 속성은 Event이벤트가 DOM을 통과 할 때 이벤트의 현재 대상을 식별합니다. Event.target이벤트가 발생한 요소를 식별하고 그 하위 요소 일 수 있는는 항상 이벤트 핸들러가 첨부 된 요소를 참조합니다.

     

    >> 하위요소고 뭐고 이벤트가 달려있는곳의 요소를 보여준다는 말이다

     

    코드를 보면

    이거는 당연한 상황이고

    target 은 내가 누른 대상이 console 에 찍히지만

    currentTarget 은 onClick 이벤트가 달려있는 요소가 찍히는 것을 확인할수 있다.

     

    이러한 특징은 

    Event.currentTarget is interesting to use when attaching the same event handler to several elements.

    mdn 에서 동일한 이벤트핸들러를 여러요소에 사용할때 효과적이라고 한다(currentTarget).

Designed by Tistory.