一、KeyboardAvoidingView
我们在开发的时候,经常会遇到手机上弹出的键盘常常会挡住当前的视图,所以这个 KeyboardAvoidingView 组件的功能就是解决这个常见问题的,它可以自动根据手机上键盘的位置,调整自身的position或底部的padding,以避免被遮挡。
1.常用属性:
1)behavior 该参数的可选值为:height, position, padding,来定义其自适应的方式
2)contentContainerStyle 如果设定behavior值为’position’,则会生成一个View作为内容容器。此属性用于指定此内容容器的样式。
3)keyboardVerticalOffset 视图离屏幕顶部有一定距离时,利用这个属性来补偿修正这段距离(键盘在竖直方向上的偏移量)
2.常用方法:
1)relativeKeyboardHeight(keyboardFrame)
2)onKeyboardChange(event) 键盘改变时回调的方法
3)onLayout(event)
3.实例代码:
<KeyboardAvoidingView
contentContainerStyle={bottomInp.contentInp}
keyboardVerticalOffset={-(totalHeight-chatAreaHeight-50)}
behavior='position'>
{...}
</KeyboardAvoidingView>
let bottomInp=StyleSheet.create({
contentInp:{
height:50,
justifyContent:'space-between',
alignItems:'center',
flexDirection:'row',
backgroundColor:'#FAFAFC',
}
}
至此,在虚拟键盘弹出时,吸底输入框高度可以自适应。但是当视图离屏幕顶部有一定距离时,为了使虚拟键盘弹出时,吸底输入框与虚拟键盘严丝合缝的配合起来。因此需要对keyboardVerticalOffset距离进行计算(负值向上偏移)。
二、UIManager、findNodeHandle
为了解决上述遗留问题,需要对RN组件的高度进行计算。我们已经知道Dimensions可以计算整屏的高度与宽度。UIManager、findNodeHandle配合使用就是用来得到组件的位置信息。
实例代码如下:
import {UIManager,findNodeHandle} from 'react-native';
render() {
let {inpText,ifFocused,plus,chatList,chatAreaHeight}=this.state;
return (
<View style={styles.container}>
<ChatArea clickHideKeyBord={this.clickHideKeyBord}
jumpBar={this.jumpBar}
jumpToNewPage={this.jumpToNewPage}
sendSelector={this.sendSelector}
chatList={chatList} ref={'chatArea'}/>
<BottomInp updateText={this.updateText}
keybordFocus={this.keybordFocus}
keybordBlur={this.keybordBlur}
clickHideKeyBord={this.clickHideKeyBord}
switchOnOff={this.switchOnOff}
sendMsg={this.sendMsg}
jumpBar={this.jumpBar}
navigation={this.props.navigation}
plus={plus}
ifFocused={ifFocused}
chatAreaHeight={chatAreaHeight}
inpText={inpText}/>
</View>
);
}
componentDidMount(){
setTimeout(()=>{
UIManager.measure(findNodeHandle(this.refs.chatArea),(x,y,width,height,pageX,pageY)=>{
let chatAreaHeight=height;
this.setState({
chatAreaHeight
})
})
},0)
}