React Rative ScrollView中嵌套TextInput定位错误的解决方案
转载请注明出处王亟亟的大牛之路
这一期有一个把一个带输入框的一个Modal改成直接显示在页面上,之前 Modal使用的是KeyboardAvoidingView
配合View
的onLayout
方法计算弹窗高度来实现效果,现在是直接迁移到页面上,所以就直接使用ScrollView
嵌套TextInput
来实现
之前的效果看这个:https://blog.****.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’,写一篇自己记录下。
谢谢!!!