React Native: TextInput auto focus 하기

Maliethy·2021년 2월 24일
2

1. issue

TextInput에 value값을 모두 작성한 후 키보드에서 '완료' 버튼을 누르면 다음 TextInput으로 auto focus하는 기능을 구현하고 싶었다.

2. solution

React Native: How to select the next TextInput after pressing the “next” keyboard button?
을 참고하여 다음과 같이 해결했다.
각 TextInput에 focus 유무를 useRef hook을 이용해 파악한다.

  const ref_input: Array<React.RefObject<TextInput>> = [];
  ref_input[0] = useRef(null);
  ref_input[1] = useRef(null);

  const onFocusNext = (index: number) => {
    if (ref_input[index + 1] && index < ref_input.length - 1) {
      ref_input[index + 1].current?.focus();
    }
    if (ref_input[index + 1] && index == ref_input.length - 1) {
      ref_input[index].current?.blur();
    }
  };

예를 들어 첫번째 TextInput에게 ref_input[0]을 TextInput 속성 중 ref 설정을 통해 할당하고

키보드 완료 버튼을 누르면 작동하는 onSubmitEditing속성에 다음과 같이 onFocusNext함수를 사용해 두번째 TextInput으로 포커스가 이동할 수 있도록 두번째 ref의 인덱스 값 1을 인수(Argument)로 넘긴다.

onSubmitEditing={() => { onFocusNext(1); }}

완성된 코드는 다음과 같다.


            <TextInput            
            value={email}
            onChangeText={onChangeEmail}
            ref={ref_input[0]}
            onSubmitEditing={() => {
              ref2.current.focus();
            }}
            returnKeyType="next"
            placeholder="이메일"
          />
          <TextInput         
            value={nickname}
            onChangeText={onChangeNickname}
            ref={ref_input[1]}
            onSubmitEditing={() => null}
            returnKeyType="done"
            placeholder="닉네임"
          />
     

ps. keyboard가 올라올 때 해당 TextInput을 화면 정가운데 오도록 조정하는 경우처럼 keyboard와 keyboard로 인해 변화된 화면을 TextInput에 따라 조정하는데 도움을 줄 수 있는 라이브러리들로 다음의 것들이 있다.

profile
바꿀 수 있는 것에 주목하자

0개의 댓글