React Rative ScrollView中嵌套TextInput定位錯誤的解決方案

轉載請註明出處王亟亟的大牛之路

這一期有一個把一個帶輸入框的一個Modal改成直接顯示在頁面上,之前 Modal使用的是KeyboardAvoidingView配合ViewonLayout方法計算彈窗高度來實現效果,現在是直接遷移到頁面上,所以就直接使用ScrollView嵌套TextInput來實現
之前的效果看這個:https://blog.csdn.net/ddwhan0123/article/details/87350792


實現效果

在這裏插入圖片描述


實現思路

使用Keyboard添加keyboardDidShowListener,keyboardDidHideListener的監聽根據不同的事件利用ScrollView自身提供的scrollTo方法使得ScrollView始終滾動到我們希望他待着的地方


實施過程

1.導入Keyboard文件

import {Keyboard} from "react-native";

2.在componentDidMountcomponentWillUnmount兩個生命週期的回調函數中添加以及移除監聽

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’,寫一篇自己記錄下。

謝謝!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章