美文网首页
小记:scrollView嵌套TextInput使用Keyboa

小记:scrollView嵌套TextInput使用Keyboa

作者: 那年那月那花儿 | 来源:发表于2024-03-12 09:46 被阅读0次

在 React Native 中,你可以使用 KeyboardAvoidingView 来避免输入框被键盘遮挡。KeyboardAvoidingView 是一个用于包裹输入框的组件,它会根据键盘的出现和消失来自动调整包裹视图的位置,以确保输入框不会被遮挡。
以下是简单使用:

const KeyboardAvoidingComponent = () => {
  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 KeyboardAvoidingComponent;

如果我们要在scrollView中使用呢,就需要整体用KeyboardAvoidingView进行包裹使用,不要在scrollView内部包裹TextInput使用,否则会导致无法触发的问题, 以下是示例:

 <SafeAreaView style={{ flex: 1 }}>
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        keyboardVerticalOffset={0}
      >
        <ScrollView style={{ flex: 1 }}>
          <Text
            style={{
              fontSize: 20,
              fontWeight: "bold",
              color: "black",
              marginBottom: 400,
            }}
          >
            Formik
          </Text>
          <MyReactNativeForm />
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>

相关文章

网友评论

      本文标题:小记:scrollView嵌套TextInput使用Keyboa

      本文链接:https://www.haomeiwen.com/subject/tfpvzdtx.html