React Native应用iOS端无法收起键盘访问发帖按钮该如何解决?
修复方案
问题原因说明
- 原布局中
InputWrapper设置了justify-content: center,当键盘弹起压缩页面可用高度时,所有内容会被挤压到顶部,导致按钮错位 - 悬浮ActionButton放在了可滚动区域内部,滚动时会跟着内容移动,出现遮挡
- 多行TextInput未设置最大高度,输入内容过多时会无限撑开,把提交按钮顶出可视区域
1. 依赖安装
先安装适配性更好的键盘避让滚动组件:
npm i react-native-keyboard-aware-scroll-view --save # 或 yarn 安装 yarn add react-native-keyboard-aware-scroll-view
2. 页面结构修改
替换原有布局结构,调整组件层级和样式:
// 顶部引入组件 import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view' import { Keyboard, TouchableWithoutFeedback } from 'react-native' // 替换return部分的代码 return ( <View style={globalStyles.container}> {/* 键盘感知滚动容器承载输入内容 */} <KeyboardAwareScrollView style={{ width: '100%' }} resetScrollToCoords={{ x: 0, y: 0 }} contentContainerStyle={{ flexGrow: 1 }} scrollEnabled={true} extraHeight={120} enableOnAndroid={true} > <TouchableWithoutFeedback onPress={Keyboard.dismiss}> {/* 修改InputWrapper对齐规则,避免内容被挤到顶部 */} <InputWrapper style={{justifyContent: 'flex-start', paddingTop: 30}}> {image != null ? <AddImage source={{ uri: image }} /> : null} <InputField placeholder="¿Qué tienes en mente?" multiline numberOfLines={4} maxHeight={200} // 限制输入框最大高度,内容过多自动滚动 value={post} onChangeText={(content) => setPost(content)} /> {uploading ? ( <StatusWrapper> <Text>{transferred} % Completed!</Text> <ActivityIndicator size="large" color="#27AE60" /> </StatusWrapper> ) : ( <SubmitBtn onPress={submitPost} style={{marginBottom: 30}}> <SubmitBtnText>Post</SubmitBtnText> </SubmitBtn> )} </InputWrapper> </TouchableWithoutFeedback> </KeyboardAwareScrollView> {/* 悬浮按钮放在滚动容器外部,固定位置不受滚动影响 */} <ActionButton buttonColor="rgb(26, 188, 156)"> <ActionButton.Item buttonColor='#9b59b6' title="New Task" onPress={() => console.log("notes tapped!")}> <Icon name="md-create" style={globalStyles.actionButtonIcon} /> </ActionButton.Item> <ActionButton.Item buttonColor='#3498db' title="Take Photp" onPress={takePhotoFromCamera}> <Icon name="camera-outline" style={globalStyles.actionButtonIcon} /> </ActionButton.Item> <ActionButton.Item buttonColor='#1abc9c' title="Elegir" onPress={choosePhotoFromLibrary}> <Icon name="md-images-outline" style={globalStyles.actionButtonIcon} /> </ActionButton.Item> </ActionButton> </View> )
3. 按需收起键盘实现
你添加的TouchableWithoutFeedback绑定Keyboard.dismiss已经实现了点击输入框外区域自动收起键盘的效果,如果需要在特定时机手动收起,直接调用Keyboard.dismiss()方法即可。
4. iOS端额外适配(可选)
如果iOS端仍存在避让不足的问题,可在ios/[项目名]/Info.plist中添加如下配置:
<key>UIViewControllerBasedStatusBarAppearance</key> <false/>
内容的提问来源于stack exchange,提问作者Miguel Espeso
相关产品推荐
相关产品推荐

