简体   繁体   中英

React Native KeyboardAvoidingView not working properly after orientation changes

while trying out KeyboardAvoidingView with the Expo Go app and npm create-react-native-app on Android I noticed a weird behaviour after a device rotation.

  1. When I launch the app in portrait mode and then switch to landscape the KeyboardAvoidingView cycles between not getting pushed up at all or not getting pushed up enough when tapping the TextInput. Also, when hiding the keyboard the button stays hidden every second time.
  2. When I launch the app in landscape mode and then switch to portrait the KeyboardAvoidingView always gets pushed up way to much.

Here is a short clip showing what happens: KeyboardAvoidingView and rotating device

How can one prevent this from happening?

Here is the code I used for create-react-native-app (I only changed the name of the component):

import React from 'react';
import {
  View,
  KeyboardAvoidingView,
  TextInput,
  StyleSheet,
  Text,
  Platform,
  TouchableWithoutFeedback,
  Button,
  Keyboard,
} from 'react-native';

const App = () => {
  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={styles.container}>
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <View style={styles.inner}>
          <Text style={styles.header}>Header</Text>
          <TextInput placeholder="Username" style={styles.textInput} />
          <View style={styles.btnContainer}>
            <Button title="Submit" onPress={() => null} />
          </View>
        </View>
      </TouchableWithoutFeedback>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  inner: {
    padding: 24,
    flex: 1,
    justifyContent: 'space-around',
  },
  header: {
    fontSize: 36,
    marginBottom: 48,
  },
  textInput: {
    height: 40,
    borderColor: '#000000',
    borderBottomWidth: 1,
    marginBottom: 36,
  },
  btnContainer: {
    backgroundColor: 'white',
    marginTop: 12,
  },
});

export default App;

Adding keyboardVerticalOffset="-999999" fixed the issue for me. It seems that after rotating the device the height of the keyboard in landscape- and portraitmode are added/subtracted from each other, leading to this weird behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM