ReactNative鍵盤遮擋TextInput解決
阿新 • • 發佈:2019-02-09
遇到的坑http://www.jianshu.com/p/fb7c718a8d9a
本週工作中開發一個小任務,將TextInput放到螢幕最下面,然後在輸入內容的時候鍵盤必須在TextInput的下方,此時就遇到了標題中所談到的問題:鍵盤遮擋住了輸入框。如下圖:
KeyboardTextInput_1.gif
當時我開發完後我用的是Android機做的測試,發現在沒有這種現象,但是在ios平臺上卻有。這對於產品來說是肯定不行的。剛開始問了一下其他同事有沒有遇到這種問題,但他們也沒有遇到過。只好求助Google了。搜了一下,別人也遇到了這種問題,現在把它記錄一下。
解決方法
export default class KeyboardTextInputComponent extends Component {
render() {
return (
<View style={styles.container}>
<ScrollView
ref="scrollView"
style={{flex: 1}}
>
<TextInput
ref="textInput"
style={styles.textInputStyle}
placeholder="請輸入內容"
onBlur={this._reset.bind(this)}
onFocus={this._onFocus.bind(this, 'textInput')}
/>
</ScrollView >
</View>
);
}
_reset() {
this.refs.scrollView.scrollTo({y: 0});
}
_onFocus(refName) {
setTimeout(()=> {
let scrollResponder = this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
ReactNative.findNodeHandle(this.refs[refName]), 0, true);
}, 100);
}
}
通過上面操作,我們再來看一下效果圖:
KeyboardTextInput_2.gif