React Native基礎:12-TextInput組件
TextInput組件簡介
TextInput組件是一個允許用戶在應用中通過鍵盤輸入文本的基本組件。這個組件提供了很多功能,比如自動完成拼寫,自動大小寫,提供占位符,還支持彈出不同類型的鍵盤等功能。
我們可以通過創建一個簡單TextInput組件看看其展示效果。在TextInput組件中,通過style屬性可以設置組件的外觀樣式,例如:寬高、背景顏色、邊框樣式等。另外還可以監聽TextInput組件與用戶的交互行為。
<TextInput
style={{height:40, borderColor: 'gray', borderWidth: 1}}
onFocus={(text) => this.setState({text})}
placeholder={'請輸入你的名字'}
/>
TextInput組件常用屬性
通過設置TextInput組件的屬性,可以設置TextInput組件的樣式以及功能特性。常用的TextInput組件的屬性可以參考下表。
| 屬性名稱 | 類型 | 說明 |
| --- | --- | --- |
|editable |bool |如果為false,文本框是不可編輯的。默認值為true。|
|keyboardType |enum |決定彈出的何種軟鍵盤的,譬如numeric(純數字鍵盤)|
|placeholder |string |如果沒有任何文字輸入,會顯示此占位文字。|
|value |string |文本框中的文字內容。|
|maxLength |number |限制文本框中最多的字符數。|
TextInput組件事件處理
TextInput組件中有幾個比較重要的事件,這些事件與用戶交互密切相關,當用戶對TextInput組件進行不同的操作時,會調用不同的函數,我們可以根據程序功能需要在不同函數中定義不同的處理邏輯。
| 函數名稱 | 類型 | 說明 |
| --- | --- | --- |
| onFocus|function |當文本框獲得焦點的時候調用此回調函數。|
| onChangeText|function |當文本框內容變化時調用此回調函數。改變后的文字內容會作為參數傳遞。|
| onEndEditing|function |當文本輸入結束后調用此回調函數。|
| onSubmitEditing|function |此回調函數當軟鍵盤的確定/提交按鈕被按下的時候調用此函數。如果multiline={true},此屬性不可用。|
下方的示例代碼中,演示了各個函數的使用方法。
<TextInput
ref='1'
style={{height:40, borderColor: 'gray', borderWidth: 1}}
onFocus={() => console.log('觸發onFocus事件')}
onChangeText={(text) => console.log('觸發onChangeText事件:'+text)}
onEndEditing={() => console.log('觸發onEndEditing事件')}
onSubmitEditing={() => console.log('觸發onSubmitEditing事件')}
placeholder={'請輸入你的名字'}
/>
示例代碼
在下方的示例代碼中,創建了一個TextInput組件以及一個Button組件,當在TextInput組件中輸入文字時,可以監聽用戶與TextInput組件的交互過程。當用戶點擊Button組件時,可以清空TextInput組件中的輸入內容。
- 在終端中執行如下命令,創建TextInputDemo工程;
react-native init TextInputDemo
- 使用Atom打開TextInputDemo工程的index.ios.js文件,編寫組件所使用的樣式
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
- 創建TextInput組件以及Button組件,并實現預期的功能。
export default class TextInputDemo extends Component {
render() {
return (
<View style={styles.container}>
<TextInput
ref='1'
style={{height:40, borderColor: 'gray', borderWidth: 1}}
onFocus={() => console.log('觸發onFocus事件')}
onChangeText={(text) => console.log('觸發onChangeText事件:'+text)}
onEndEditing={() => console.log('觸發onEndEditing事件')}
onSubmitEditing={() => console.log('觸發onSubmitEditing事件')}
placeholder={'請輸入你的名字'}
/>
<Button
onPress={(text) => this.refs['1'].clear()}
title="點擊按鈕清除輸入內容"
/>
</View>
);
}
}
- 使用import加載項目所使用的模塊,并且注冊組件TextInputDemo成為整個應用的根容器。
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
TextInput,
Button,
} from 'react-native';
AppRegistry.registerComponent('TextInputDemo', () => TextInputDemo);
- 在終端中執行下面的命令運行程序,在iOS模擬器中可以看到創建的TextInput組件和Button組件。
react-native run-ios
- 打開iOS模擬器的日志,當用戶在TextInput組件中輸入內容時,可以通過日志查看器看到TextInput組件的事件處理函數被調用。