解決iOS中彈出鍵盤遮擋輸入框的問題, 需要在輸入框獲取焦點時向上移動一定的距離. 有一個比較簡單的方法
首先要將輸入框的父組件改為scrollView, 這樣就可以根據需要進行移動,并設置ref, 方便控制scrollView滾動
在輸入框的onFocus方法中添加如下代碼, 就可以實現輸入框隨鍵盤彈出而移動
/**
* this.refs.scrollView : 根據scrollView組件的ref獲取該組件
* findNodeHandle : import {findNodeHandle} from 'react-native';
* inputRef : 輸入框的ref字符串
* distance : 輸入框距離鍵盤頂部的間距
*/
setTimeout(()=> {
let scrollResponder = this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
findNodeHandle(inputRef, distance, true);
}, 100);
- 當輸入框失去焦點時, 需要再次調用第二步的方法將輸入框移動回底部 (最好是將輸入框移動回原位置,目前我還沒找到方法). 但是不是在onBlur方法中調用. 因為界面有多個輸入框的話, 切換輸入框會出現問題. 最好添加鍵盤事件監(jiān)聽, 當鍵盤隱藏時才調整輸入框的位置
/**
* Keyboard : import {Keyboard} from 'react-native';
*/
componentWillMount() {
this.keyboardWillHideListener = Keyboard.addListener('keyboardWillHide',this._keyboardWillHideHandler.bind(this));
}
componentWillUnmount() {
this.keyboardWillHideListener.remove();
}
/**
* this.state.input : 在輸入框onFocus方法中將當前選中輸入框的ref保存到state中,
*/
_keyboardWillHideHandler() {
this.state.inputRef && this.avoidKeyboardCover(this.state.inputRef,80);
}
這樣就解決了鍵盤遮擋輸入框的問題. 雖然有一點瑕疵, 輸入框不能回到原來的位置, 但是已經可以滿足基本需要, 比起使用第三方組件要輕便很多, 是一個不錯的選擇