bravo my life!

[React-Native] TextInput에 입력 후 다음 TextInput으로 이동하기 본문

Framework || Library/React-Native

[React-Native] TextInput에 입력 후 다음 TextInput으로 이동하기

losajjang 2022. 8. 14. 09:53
728x90

1. 개요

TextInput이 여러개가 있다고 생각하자.

첫번째 인풋 입력 후, 두번째 인풋으로 이동하는 방법은 인풋을 터치하는 방법이 있겠지만

사용자의 엄지손가락은 이미 키보드에 있다.

엄지손가락의 이동을 최소화하려면 키보드 배열 안에서 다음 인풋으로 이동시키는 버튼이 있어야 할 것이다.

2. useRef 이용

import React, {useCallback, useRef, useState} from 'react';
import {
  Alert,
  Pressable,
  StyleSheet,
  Text,
  TextInput,
  View,
} from 'react-native';

function SignIn() {
  ...

  const secondInput = useRef<TextInput>(null);

  return (
    <View>
      <View style={styles.inputWrapper}>
        <Text style={styles.label}>이메일</Text>
        <TextInput
          style={styles.textInput}
          placeholder="이메일을 입력해주세요."
          value={email}
          onChangeText={onChangeEmail}
          importantForAutofill="yes"
          autoComplete="email"
          textContentType="emailAddress"
          returnKeyType="next"
          onSubmitEditing={() => {
            secondInput.current?.focus();
          }}
        />
      </View>
      <View style={styles.inputWrapper}>
        <Text style={styles.label}>비밀번호</Text>
        <TextInput
          ref={secondInput}
          style={styles.textInput}
          placeholder="비밀번호를 입력해주세요."
          value={password}
          onChangeText={onChangePassword}
          secureTextEntry
          importantForAutofill="yes"
          autoComplete="password"
          textContentType="password"
          returnKeyType="done"
        />
      </View>
      ...
    </View>
  );
}

useRef를 이용하여 secondInput 변수를 만들었고 특정 DOM 선택하기와 같은 기능으로 사용했다.

중요한 것은 타입 지정이다. <TextInput>으로 타입을 지정했다.

onSubmitEditing={()=>{secondInput.current.focus()}} 으로 현재의 ref를 가리키도록 했고 터치 키보드의 넥스트버튼을 터치시

ref={secondInput} 으로 focus가 이동한다.