키보드 이벤트 한글 조합 버그 수정하기

가은·2024년 11월 12일
0

사진처럼 입력하다가 방향키를 조작하면 바로 아래로 내려오면서 선택되어야하는데 첫번째 값이 자꾸 건너뛰어지는 현상이 있었다.
콘솔 찍었을때 인덱스는 0으로 찍히는데 결과적으로 1까지 혼자 증가해서 화면상으론 0번째로 안내려온다.

이벤트가 문제 같았긴 한데 한글 조합 이벤트 문제일 줄은,,,😭

한글 입력 상태를 추적하는 ref를 걸어서 이벤트를 처리하니까 간단하게 해결되었다.

  1. 한글 입력할 때 (ㅅ, ㅓ, ㅇ 등) 각각의 자음/모음이 개별 키 이벤트를 발생시킴
  2. isComposing ref를 추가하여 한글 조합 상태를 추적
  3. onCompositionStart와 onCompositionEnd 이벤트 핸들러를 추가하여 한글 입력 시작과 끝을 감지

이렇게 되면 한글 입력 중에는 키보드 네비게이션이 동작하지 않고, 한글 입력이 완성된 후에만 키보드 네비게이션이 동작한다.

  const isComposing = useRef(false); // 한글 조합 상태 추적

  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    // 한글 입력 중일 때는 키 이벤트를 무시
    if (isComposing.current) {
      return;
    }

    if (!isDropdownOpen || filteredSchools.length === 0) return;

    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setActiveIndex(prevIndex => {
        if (prevIndex === -1) return 0;
        return Math.min(prevIndex + 1, filteredSchools.length - 1);
      });
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setActiveIndex(prevIndex => {
        if (prevIndex <= 0) return filteredSchools.length - 1;
        return prevIndex - 1;
      });
    } else if (e.key === 'Enter' && activeIndex >= 0) {
      e.preventDefault();
      handleSelectSchool(filteredSchools[activeIndex]);
    }
  };

  return (
     <input
        onCompositionStart={() => {
          isComposing.current = true;
        }}
        onCompositionEnd={() => {
          isComposing.current = false;
        }}
      />
  )
profile
일이 재밌게 진행 되겠는걸?

0개의 댓글