Programming/React Native

[React Native] KeyboardAvoidingView & ScrollView 사용법

리버김 2022. 12. 15.
회원 로그인 화면에서 input을 클릭했을 때 키보드가 위로 올라가게 되는데, 이 떄 하단의 내용 일부가 키보드에 가려지는 문제가 있었다. 그래서 React Native의 KeyboardAvoidingView와 그 내부의 ScrollView를 활용해 문제를 해결했다.

LoginScreen.js

...
<KeyboardAvoidingView style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 40}
    >
      <ScrollView style={styles.topView}
        contentContainerStyle={{flexGrow: 1}}
      >
        <View style={styles.idView}>
          <View style={styles.inputRow}>
            <Image source={loginIdIcon} style={styles.inputIcons} />
            <Text style={styles.inputText}>회원 아이디</Text>
          </View>
...

 

먼저 기존의 최상위 View를 KeyboardAvoidingView로 교체한다. 두 가지 인자를 볼 수 있는데, 첫째는 behavior이고, 둘째는 keyboardVerticalOffset이다.

behavior

behavior는 키보드가 올라왔을 때, 기존 화면이 어떻게 동작할지를 정하는 인자다.

 

1. height

input창이 키보드로부터 keyboardVerticalOffset 거리만큼 위치하게 된다.

아직 왜인지는 모르지만, android에서는 height를 쓰는 용례가 많아서 그렇게 적용했다. 

 

2. position

input이 기존에 위치한 만큼 상대적으로 키보드로부터 위치하게 된다. 기존에 View의 맨 아래 있으면 키보드에 붙어 올라오고, 조금 떨어져 있으면 그만큼 떨어져 나온다.

 

3. padding

키보드로부터 keyboardVerticalOffset만큼 padding을 만든다.

height과 비슷한데, 설정한 padding만큼 추가하여 적용된다.

 

keyboardVerticalOffset

keyboardVerticalOffset은 추가로 지정할 수 있는 키보드와의 거리다. 기기, OS 별로 차이가 있기 때문에 Platform을 import 해서 사용하는 용례가 많았다. 우선은 안드로이드(내 휴대전화)에서만 테스트 해본 상태이기에 ios에서는 0을 주었다.

 

https://blog.hackajob.co/using-the-keyboardavoidingview-in-react-native/

 

Using the KeyboardAvoidingView in React Native

This week, we’re going to be learning how to use and implement the KeyboardAvoidingView.

blog.hackajob.co

https://hsl1697.tistory.com/57

 

Final Project - (11) 2020_0208

이번에는 로그인 컴포넌트를 만들 차례이다. 그전에 저번에 회원가입 컴포넌트를 만들면서 2가지 이슈가 있었는데, 한가지는 axios이고 다른 건 keyboardavoidingview이다. axios에 관한 것은 조금 있다

hsl1697.tistory.com

 

그리고서는 모두 끝났다고 생각했지만, styles 컴포넌트에서 ScrollView에 해당하는 부분에 alignitems를 적용헀더니 'scrollview child layout ( alignitems ) must be applied through the contentcontainerstyle prop'이라는 에러가 발생했다.

 

이유는 ScrollView 자체에 flex 설정을 해주지 않았기 때문이다. 따라서 contentContainerStyle={{ flexGrow: 1 }}라는 옵션으로 flex를 적용해주어야 하는 것이었다.

 

KeyboardAvoidingView · React Native

This component will automatically adjust its height, position, or bottom padding based on the keyboard height to remain visible while the virtual keyboard is displayed.

reactnative.dev

 

 

ScrollView · React Native

Component that wraps platform ScrollView while providing integration with touch locking "responder" system.

reactnative.dev

반응형

댓글