在 react-native 中打开键盘时,ScrollView 无法滚动到底部。[IOS]

关闭键盘时,Scrollview 工作正常。但是当键盘打开时,它不会滚动到底部。不过,它在 Android 中运行良好。问题仅出在 iOS 上。

如果我使用 react-native-keyboard-aware-scroll-view ,那么问题就解决了,但我不想使用这个包。

我的工作环境:-

世博会 SDK:- 40

平台:- IOS

import React from "react";
import {
  ScrollView,
  TextInput,
  SafeAreaView,
  TouchableOpacity,
  Text,
} from "react-native";

function App() {
  return (
    <SafeAreaView style={{ flex: 1 }}>
      <ScrollView style={{ flex: 1 }}>
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TextInput style={{ borderWidth: 2, height: 50, marginVertical: 10 }} />
        <TouchableOpacity
          style={{ height: 50, backgroundColor: "red", marginVertical: 10 }}
        >
          <Text>Button</Text>
        </TouchableOpacity>
      </ScrollView>
    </SafeAreaView>
  );
}

export default App;
stack overflow ScrollView can not scroll to the bottom when keyboard is open in react-native.[IOS]
原文答案

答案:

作者头像

您可以像这样使用 KeyboardAwareScrollView :

<KeyboardAwareScrollView  keyboardShouldPersistTaps={'always'}
        style={{flex:1}}
        showsVerticalScrollIndicator={false}>
    {/* Your code goes here*/}
</KeyboardAwareScrollView>

还有一些额外的事情你可以做我使用样式表而不是每次添加文本输入的样式这里是一个例子:

import {StyleSheet} from 'react-native

function App() {
  return (
    <SafeAreaView style={{ flex: 1 }}>
      <TextInput style={styles.textInput} />
      <TextInput style={styles.textInput} />
      <TextInput style={styles.textInput} />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  textInput: {
    borderWidth: 2, 
    height: 50, 
    marginVertical: 10
});

如果您想了解更多有关 KeyboardAwareScrollView 的信息,您可以访问此处: https://github.com/APSL/react-native-keyboard-aware-scroll-view

以及更多关于样式表的信息: https://reactnative.dev/docs/stylesheet

作者头像

您可以使用keyboardAvoidingView, see the doc

例如:

<KeyboardAvoidingView
   style={styles.container}
   behavior="padding"
/>