1.在写react native时会碰到弹起的键盘遮挡住输入框的问题
官网给出了解决方案:https://reactnative.cn/docs/keyboardavoidingview#docsNav
keyboardavoidingview可以解决这个问题
需要给参数behavior={"position/height/padding"}
keyboardVerticalOffset给值一般是给键盘的高度
2.rn获取键盘高度方法
import { Keyboard } from 'react-native';
keyboardDidShowListener;
keyboardDidHideListener;
componentWillMount(){
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow',
this._keyboardDidShow.bind(this));
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide',
this._keyboardDidHide.bind(this));
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
//this.keyboardDidHideListener.remove();
}
_keyboardDidShow(e){
const { getKeyBoardHeight } = this.props;
getKeyBoardHeight && getKeyBoardHeight(e.endCoordinates.height);
this.setState({
keyboardHeight:e.endCoordinates.height
})
}
_keyboardDidHide(e){
this.setState({
keyboardHeight:0
})
}
这里监听键盘弹起时返回的对象里,endCoordinates 和 startCoordinates的区别是?
3.接下来又出现显得问题,在页面偏下的输入框可以被顶起看可视区内,但是在页面顶部的输入框可能就被顶出可视区外了。所以这里又需要判断输入框在页面的位子了。根据输入框在页面的位子设置keyboardVerticalOffset的值。
但是也有遇到设置keyboardVerticalOffset为0不生效的情况,此时可以禁用keyboardavoidingview enabled = true;
import {NativeModules, findNodeHandle } from 'react-native';
const UIManager = NativeModules.UIManager;
UIManager.measure(findNodeHandle(ref),(x,y,width,height,pageX,pageY)=>{
console.log(x,y,width,height,pageX,pageY,clientHeight)
})