基礎篇章:關於 React Native 之 KeyboardAvoidingView 元件的講解
阿新 • • 發佈:2022-04-28
友情提示:RN學習,從最基礎的開始,大家不要嫌棄太基礎,會的同學請自行略過,希望不要耽誤已經會的同學的寶貴時間)
看完了這個元件的名字 KeyboardAvoidingView ,你們心裡肯定會想這是個什麼東西,Keyboard 大家肯定知道是鍵盤,那是關於鍵盤的什麼呢?Avoiding 是避免,迴避的意思,這會大家估計知道什麼了吧?鍵盤避免檢視元件,我們在開發的時候,經常會遇到手機上彈出的鍵盤常常會擋住當前的檢視,所以這個 KeyboardAvoidingView 元件的功能就是解決這個常見問題的,它可以自動根據手機上鍵盤的位置,調整自身的position或底部的padding,以避免被遮擋。
屬性和方法
老樣子,我們先來看看 KeyboardAvoidingView 元件的屬性,只有瞭解了這些屬性和方法,我們才能運用自如,屬性如下:
- behavior 位移焦點時就使用哪個屬性來自適應,該引數的可選值為:height, position, padding
- contentContainerStyle 如果設定behavior值為'position',則會生成一個View作為內容容器。此屬性用於指定此內容容器的樣式。
- keyboardVerticalOffset 可能應用檢視離螢幕頂部有一些距離,利用這個屬性來補償修正這段距離(鍵盤在豎直方向上的偏移量) 看完屬性,我們再看看幾個簡單的方法:
- relativeKeyboardHeight(keyboardFrame)
- onKeyboardChange(event) 鍵盤改變時回撥的方法
- onLayout(event)
例項演示
照例,在例項程式碼之前,我們先看看效果圖,這次我們看一個簡單的對比圖,在不使用 KeyboardAvoidingView 的情況下,看看是什麼樣子,使用了 KeyboardAvoidingView 元件的情況下,又是一種什麼情況。
沒有使用 KeyboardAvoidingView 前的效果圖:
看看,是不是擋住了輸入框的一半,很不人性化。那我們就再看看使用了 KeyboardAvoidingView 之後的效果如何?如下:
例項程式碼
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
KeyboardAvoidingView,
View
} from 'react-native';
export default class KeyboardAvoidingViewDemo extends Component {
state = {
behavior: 'padding',
};
render() {
return (
<View style={styles.container}>
<KeyboardAvoidingView behavior="padding" style={styles.container}>
<TextInput
underlineColorAndroid={'#ffffff'}
placeholder="這裡是一個簡單的輸入框"
style={styles.textInput} />
</KeyboardAvoidingView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor:'white',
justifyContent: 'center',
paddingHorizontal: 20,
paddingTop: 20,
},
textInput: {
borderRadius: 5,
borderWidth: 1,
height: 140,
paddingHorizontal: 10,
},
});
AppRegistry.registerComponent('KeyboardAvoidingViewDemo', () => KeyboardAvoidingViewDemo);