React Native基礎:13-KeyboardAvoidingView組件
KeyboardAvoidingView組件簡介
目前市面上的智能手機基本上,用戶都是使用虛擬鍵盤(軟鍵盤)來輸入內容,使用實體鍵盤的智能手機幾乎已經銷聲匿跡了。用戶輸入習慣的變化,隨之而來的一個問題就是手機上彈出的鍵盤常常會擋住當前的視圖,導致用戶不知道應該輸入的是什么內容。KeyboardAvoidingView組件就是用來解決這個尷尬的問題的,它能在彈出鍵盤的時候將視圖整體上移,從而避免界面內容被鍵盤蓋住。
一般來說,KeyboardAvoidingView組件經常會用在有輸入框的界面,比較常見的有登錄界面、用戶資料修改頁面、IM軟件的聊天界面等。
KeyboardAvoidingView組件通過behavior屬性來控制鍵盤彈出之后的組件行為。behavior屬性有三個值:height、padding和postion。通常情況下,我們只考慮padding和position即可,height會改變視圖的高度,導致鍵盤回收后不能回到原來的位置。
- padding:通過設置KeyboardAvoidingView的paddingBottom樣式的值,來改變內容的位置。
- position:新建一個視圖作為子組件的容器,并且通過設置視圖bottom樣式的值,來改變內容的位置。
示例代碼
我們通過一個示例代碼來學習使用KeyboardAvoidingView組件實現界面的整體向上移動的方法。在該案例中,我們在KeyboardAvoidingView組件中添加兩個子組件,一個是SegmentedControlIOS組件,用于切換behavior屬性的值,另外一個TextInput組件,當用戶點擊TextInput組件開始輸入時,KeyboardAvoidingView組件會根據SegmentedControlIOS組件的當前值選擇界面上移的方式。
- 在終端中執行如下命令,創建KeyboardAvoidingViewDemo工程;
react-native init KeyboardAvoidingViewDemo
- 使用Atom打開工程的index.ios.js文件,編寫組件所使用的樣式
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingHorizontal: 20,
paddingTop: 20,
},
textInput: {
borderRadius: 5,
borderWidth: 1,
height: 44,
paddingHorizontal: 10,
top: 10,
},
});
- 構建界面。在KeyboardAvoidingView組件中添加一個SegmentedControlIOS組件以及一個TextInput組件。
export default class KeyboardAvoidingViewDemo extends Component {
state = {
behavior: 'padding',
};
render() {
return (
<View style={styles.container}>
<KeyboardAvoidingView behavior={this.state.behavior} style={styles.container}>
<SegmentedControlIOS
onValueChange={this.onSegmentChange}
selectedIndex={this.selectedIndex()}
style={styles.segment}
values={['Padding', 'Position']} />
<TextInput
placeholder="<TextInput />"
style={styles.textInput} />
</KeyboardAvoidingView>
</View>
);
}
}
- 在KeyboardAvoidingViewDemo組件中,通過設置SegmentedControlIOS組件selectedIndex屬性來初始化界面。
selectedIndex = () => {
switch (this.state.behavior) {
case 'padding':
return 0;
case 'position':
return 1;
default:
return 0;
}
}
- 在KeyboardAvoidingViewDemo組件中,通過處理SegmentedControlIOS的選擇事件來修改KeyboardAvoidingView的behavior屬性。
onSegmentChange = (segment: String) => {
this.setState({behavior: segment.toLowerCase()});
};
- 使用import加載項目所使用的模塊,并且注冊組件KeyboardAvoidingViewDemo成為整個應用的根容器。
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
KeyboardAvoidingView,
SegmentedControlIOS,
TextInput,
} from 'react-native';
AppRegistry.registerComponent('KeyboardAvoidingViewDemo', () => KeyboardAvoidingViewDemo);
- 在終端中執行下面的命令運行程序。到現在為止,我們就可以通過切換SegmentedControlIOS組件的不同選項來體驗這兩種行為的區別了。
react-native run-ios