今天,偶然翻Github发现了KeyboardAvoidingView,原来FaceBook的开发者们也意识到了键盘遮挡的问题。
从0.31版本开始,提供了官方的解决方案。
源码地址如下:https://github.com/facebook/react-native/blob/master/Libraries/Components/Keyboard/KeyboardAvoidingView.js
使用方法如下:
- <KeyboardAvoidingView behavior='padding'>
- <View style={styles.textInputContainer}>
- <TextInput
- value={this.state.data}
- style={styles.textInput}
- onChangeText={this.handleChangeData}
- />
- </View>
- </KeyboardAvoidingView>
KeyboardAvoidingView的主要属性behavior PropTypes.oneOf(['height', 'position', 'padding'])
这个三个属性什么意思?我也不知道,那就一个个试吧!
Demo如下:
-
-
-
-
-
-
-
-
-
-
- 'use strict';
-
- const React = require('React');
- const ReactNative = require('react-native');
- const {
- KeyboardAvoidingView,
- Modal,
- SegmentedControlIOS,
- StyleSheet,
- Text,
- TextInput,
- TouchableHighlight,
- View,
- Dimensions,
- ScrollView,
- } = ReactNative;
- const {width, height} = Dimensions.get('window');
-
- export default class KeyboardAvoidingViewExample extends React.Component {
-
-
- constructor(props) {
- super(props);
- }
-
- render() {
- return (
- <KeyboardAvoidingView behavior='position' >
- <ScrollView style={styles.outerContainer}>
- <View style={styles.container}>
- <View style={{height:400,backgroundColor:'red',justifyContent:'center',alignItems:'center',}}>
- <Text style={{fontSize:28,color:'#998462',textAlign:'center',}}>Top Area</Text>
- </View>
- <TextInput
- placeholder="<TextInput />"
- style={styles.textInput} />
- <View style={{height:200,backgroundColor:'blue',justifyContent:'center',alignItems:'center',}}>
- <Text style={{fontSize:28,color:'#998462',textAlign:'center',}}>Bottom Area</Text>
- </View>
- </View>
- </ScrollView>
- </KeyboardAvoidingView>
- );
- }
- }
-
- const styles = StyleSheet.create({
- outerContainer: {
- height:height,
- paddingTop: 20,
- },
- container: {
- flex: 1,
- justifyContent: 'center',
- },
- textInput: {
- borderRadius: 5,
- borderWidth: 1,
- height: 44,
- paddingHorizontal: 10,
- },
- });
页面逻辑很简单,模拟表单输入:一个Scrollview,由于表单页面的高度超过了屏幕的高度,所以是带滚动轮的。
里面的内容分3块:上面一个View,中间一个Textinput,下面一个View
页面显示如下:
1、我们先设置KeyboardAvoidingView behavior='padding'
发现设置为padding后并没有解决键盘被覆盖的问题,后来我想是不是因为里面有Scrollview组件的问题,尝试去掉Scrollview组件,将Scrollview改为View就可以了。
可是,我们通常的输入表单都是用Scrollview嵌套的啊???这个问题怎么解?
效果如下:
2、我们再设置KeyboardAvoidingView behavior='position'
效果如下:
我反复修改Bottom Area 的高度值,发现设置为position时,只是单纯的将当前TextInput的位置上移了 一个键盘的高度。
这样其实也是有问题的,譬如这种情况:
当前输入时,我们的TextInput就已经处于屏幕的顶端,如果再上移一个键盘的高度,那么我的TextInput是不可见的。
3、我们再设置KeyboardAvoidingView behavior='height'
没有任何效果,将Scrollview修改为View,也没有任何效果。
如果大家感兴趣也可以试下,感觉KeyboardAvoidingView的坑很多啊。
如果大家对KeyboardAvoidingView组件的使用有什么好的方法,可以留言告诉我,谢谢!
备注:以上实验是只在iPhone5s 系统 iOS10.1模拟器上进行。
实验版本:"React-native": "0.35.0"