RN之KeyboardAvoidingView、UIManager、findNodeHandle的使用

一、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)
  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值