解決iOS中彈出鍵盤遮擋輸入框的問題, 需要在輸入框獲取焦點(diǎn)時(shí)向上移動(dòng)一定的距離. 有一個(gè)比較簡單的方法
首先要將輸入框的父組件改為scrollView, 這樣就可以根據(jù)需要進(jìn)行移動(dòng),并設(shè)置ref, 方便控制scrollView滾動(dòng)
在輸入框的onFocus方法中添加如下代碼, 就可以實(shí)現(xiàn)輸入框隨鍵盤彈出而移動(dòng)
/**
* this.refs.scrollView : 根據(jù)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);
- 當(dāng)輸入框失去焦點(diǎn)時(shí), 需要再次調(diào)用第二步的方法將輸入框移動(dòng)回底部 (最好是將輸入框移動(dòng)回原位置,目前我還沒找到方法). 但是不是在onBlur方法中調(diào)用. 因?yàn)榻缑嬗卸鄠€(gè)輸入框的話, 切換輸入框會(huì)出現(xiàn)問題. 最好添加鍵盤事件監(jiān)聽, 當(dāng)鍵盤隱藏時(shí)才調(diào)整輸入框的位置
/**
* Keyboard : import {Keyboard} from 'react-native';
*/
componentWillMount() {
this.keyboardWillHideListener = Keyboard.addListener('keyboardWillHide',this._keyboardWillHideHandler.bind(this));
}
componentWillUnmount() {
this.keyboardWillHideListener.remove();
}
/**
* this.state.input : 在輸入框onFocus方法中將當(dāng)前選中輸入框的ref保存到state中,
*/
_keyboardWillHideHandler() {
this.state.inputRef && this.avoidKeyboardCover(this.state.inputRef,80);
}
這樣就解決了鍵盤遮擋輸入框的問題. 雖然有一點(diǎn)瑕疵, 輸入框不能回到原來的位置, 但是已經(jīng)可以滿足基本需要, 比起使用第三方組件要輕便很多, 是一個(gè)不錯(cuò)的選擇