在移动端上,输入框被软键盘遮挡是一个非常常见的问题,为此,RN原生的提供了一个组件 KeyboardAvoidingView 来处理这个问题,KeyboardAvoidingView的主要属性behavior 包含三个’height’, ‘position’, ‘padding’, 使用最多的就是 padding。但这个组件有时候使用起来可能失效。所以,需要找寻其他的方法
方法一:KeyboardAvoidingView(仔细研究研究,试一试说不定就可以了呢)
方法二:每次输入框聚焦时,获取软件盘的高度,然后让输入框上移;大致代码如下:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Keyboard,
TextInput,
Dimensions
} from 'react-native';
var ScreenWidth = Dimensions.get('window').width;
export default class Root extends Component {
// 构造
constructor(props) {
super(props);
// 初始状态
this.state = {
keyboardHeight:0
};
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
<TextInput
style={{width:ScreenWidth,height:100,borderWidth:2,marginBottom:this.state.keyboardHeight}}
/>
</View>
);
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
componentWillMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
}
_keyboardDidShow(e){
this.setState({
keyboardHeight:e.startCoordinates.height
})
}
_keyboardDidHide(e){
this.setState({
keyboardHeight:0
})
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
方法三:将 View 组件换成 native-base 的 Content 组件(简单,好用)
文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出!