在 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>
网友评论