React Native(Expo CLI)中KeyboardAvoidingView无法解决键盘遮挡TextInput问题
React Native Expo 键盘遮挡TextInput问题修复方案
问题根因
你当前的代码存在3个核心问题导致KeyboardAvoidingView不生效:
- 根容器
MainContainer、KeyboardAvoidingView、ScrollView都缺少flex: 1样式,没有占满全屏高度的情况下,组件无法计算键盘弹出后的偏移量 - 安卓端使用
behavior="height"容易出现高度计算错误,改用padding兼容性更好 - ScrollView缺少
keyboardShouldPersistTaps属性,会影响输入框聚焦后的滚动逻辑
修复后代码
// import 部分保留,新增引入Platform、StatusBar按需使用 import { Platform, StatusBar } from 'react-native' return ( // 确认style.MainContainer已经配置flex: 1,如果没有就在标签上加style={{flex:1}} <View style={[style.MainContainer, {flex: 1}]}> <View style={style.chooseDpContainer}> <TouchableOpacity onPress={openImagePickerAsync} style={style.chooseDpContainer}> {(!ImageUrl)?( <> <Avatar.Icon size={70} icon="camera-plus-outline" style={{marginEnd:10}} /> <Text>给你的宠物选个好看的头像</Text> </> ):( <> <Avatar.Image size={70} source={{uri:ImageUrl}} style={{marginEnd:10}}/> <Text>换一张图片?</Text> <Button mode="text" icon="delete" style={{fontSize:40}} onPress={()=>{ setImageUrl('') }}>删除</Button> </> )} </TouchableOpacity> </View> <View style={style.divider} ></View> <Text style={{marginBottom:10}}>你的宠物信息</Text> {/* 修复后的键盘适配区域 */} <KeyboardAvoidingView style={{width:'100%', flex: 1}} behavior={Platform.OS==="ios"?'padding':"padding"} // 如果顶部有自定义导航栏可以调整偏移量,示例为适配原生状态栏高度 keyboardVerticalOffset={StatusBar.currentHeight || 0} > <ScrollView style={{width:'100%', flex: 1}} keyboardShouldPersistTaps="handled" > <View style={style.Input}><TextInput label="名字"/></View> <View style={style.Input}><TextInput label="年龄"/></View> <View style={style.Input}><TextInput label="品种"/></View> <View style={style.Input}><TextInput label="性别"/></View> </ScrollView> </KeyboardAvoidingView> </View> ) }
额外检查项
如果修改后还是无效,检查Expo项目的app.json配置,确认安卓端的软键盘布局模式设置为adjustResize:
{ "expo": { "android": { "softwareKeyboardLayoutMode": "adjustResize" } } }
内容的提问来源于stack exchange,提问作者Narendra Dewasi
相关产品推荐
相关产品推荐

