[React] input의 onChange 이벤트 dispacthEvent로 트리거하기

mosad2334·2022년 9월 16일
0

React에서 특정 컴포넌트의 버튼을 클릭할 시 다른 컴포넌트의 인풋의 onChange 이벤트를 트리거하려고 dispatchEvent를 사용했는데 작동이 무시됐음.
onClick, onFocus, onKeyUp같은 경우는 dispatchEvent로 잘 됐는데 정작 딱 원하는 기능이 안돼서 깔끔하지 않아 해결방법 뒤지 시작함.

Trigger change events when the value of an input changed programmatically React

여기서

What is the best way to trigger onchange event in react js

여기로 타고 들어갔음
이유는 다음과 같다고 함

Setter .value= is not working as we wanted because React library overrides input value setter but we can call the function directly on the input as context.

TS라서 다음과 같이 해결
state.activeElement는 HTMLInputElement | null | undefined,
event.currentTarget.getAttribute("data-key")가 인풋의 onChange 트리거를 건드리며 입력되는 값.

이게 최선인가 싶긴 한데 더 나은 방법이 생각이 안나고 일단 상당히 시간이 걸려서 기록.

word-crusher/src/components/keyboard/Keyboard.tsx

const onClick = (event: MouseEvent<HTMLButtonElement>) => {
    state.activeElement?.focus();
    Object?.getOwnPropertyDescriptor(
      window.HTMLInputElement.prototype,
      "value"
    )?.set?.call(
      state.activeElement,
      event.currentTarget.getAttribute("data-key")
    );
    state.activeElement?.dispatchEvent(new Event("change", { bubbles: true }));
  };
profile
Web Developer / Read "KEEP CALM CARRY ON" Poster

1개의 댓글

comment-user-thumbnail
2023년 6월 21일

하루종일 삽질했는데 덕분에 해결했습니다...진짜 감사합니다...

답글 달기