轉載請註明出處王亟亟的大牛之路
這一期有一個把一個帶輸入框的一個Modal改成直接顯示在頁面上,之前 Modal使用的是KeyboardAvoidingView
配合View
的onLayout
方法計算彈窗高度來實現效果,現在是直接遷移到頁面上,所以就直接使用ScrollView
嵌套TextInput
來實現
之前的效果看這個:https://blog.csdn.net/ddwhan0123/article/details/87350792
實現效果
實現思路
使用Keyboard添加keyboardDidShowListener
,keyboardDidHideListener
的監聽根據不同的事件利用ScrollView
自身提供的scrollTo
方法使得ScrollView
始終滾動到我們希望他待着的地方
實施過程
1.導入Keyboard文件
import {Keyboard} from "react-native";
2.在componentDidMount
和componentWillUnmount
兩個生命週期的回調函數中添加以及移除監聽
2.1 添加監聽
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
this._keyboardDidShow,
);
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
this._keyboardDidHide,
);
}
2.2 移除監聽
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
2.3 實現監聽回調
_keyboardDidShow = () => {
this.scrollToBottom(this);
};
_keyboardDidHide = () => {
this.scrollToBottom(this);
};
//我這裏實現是永遠回到最下面
scrollToBottom(that) {
let refData = that.refs._scrollView;
this._timer && clearTimeout(this._timer);
this._timer = setTimeout(() => {
refData.scrollToEnd({animated: true});
}, 150);
};
2.4 被關聯的列表
<ScrollView
ref="_scrollView"
style={{ flex: 1}}>
<View>
<TextInput/>
........
</View>
</ScrollView>
整體實現比較簡單,爲什麼寫這篇主要是網上一大堆要麼用第三方的,要麼各種寫死的’padding’,寫一篇自己記錄下。
謝謝!!!