[React Native] Prevent the On-screen Keyboard from Covering up Text Inputs

本文介绍了ReactNative中处理软键盘遮挡输入框的问题。通过使用内置组件KeyboardAvoidingView和第三方库KeyboardAwareScrollView,可以有效避免软键盘弹出时覆盖输入框的情况,提升用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When you bring up the on screen keyboard in a mobile app, it will cover any text input or buttons on the bottom half of the screen, which can be frustrating for users. There are a few common ways to deal with this in React Native - and this video shows the following solutions:

First, you can use the built in KeyboardAvoidingView to move components around when the keyboard comes on screen. It has the advantage to being built in to React Native already - but it can be overly complicated to get this approach to work consistently across both iOS and Android.

There is also a third party library called KeyboardAwareScrollView, which will allow your entire view to scroll, and will keep the currently selected text inputs up and out of the way of the keyboard.

 

Install:

npm i -D react-native-keyboard-aware-scroll-view

 

Use:

import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'

export default class App extends Component {
  render() {
    return (
      <KeyboardAwareScrollView
        style={{ flex: 1 }}
      >

          <View style={styles.loginHeader}>
            <Text style={styles.headerText}>App Name</Text>
          </View>

          <View style={styles.loginInputs}>
            <Text style={styles.label}>Username</Text>
            <TextInput 
              placeholder="Username"
              style={styles.input}
            />
            <Text style={styles.label}>Password</Text>
            <TextInput 
              placeholder="Password"
              style={styles.input}
              secureTextEntry={true} 
            />
            <TouchableOpacity style={styles.loginButton}>
              <Text style={styles.loginText}>Login</Text>
            </TouchableOpacity>
          </View>

      </KeyboardAwareScrollView>
    );
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值