TextInput是一個允許用戶輸入文本的基礎組件。它有一個名為onChangeText的屬性,此屬性接受一個函數,
而此函數會在文本變化時被調用。另外還有一個名為onSubmitEditing的屬性,
會在文本被提交后(用戶按下軟鍵盤上的提交鍵)調用。
假如我們要實現當用戶輸入時,實時將其以單詞為單位翻譯為另一種文字。我們假設這另一種文字
來自某個吃貨星球,只有一個單詞: 🍕。所以"Hello there Bob"將會被翻譯為"🍕🍕🍕"。

import React, { Component } from 'react';
import { AppRegistry, Text, TextInput, View } from 'react-native';
export default class PizzaTranslator extends Component {
constructor(props) {
super(props);
this.state = {text: ''};
}
render() {
return (
<View style={{padding: 10}}>
<TextInput
style={{height: 40}}
placeholder="Type here to translate!"
onChangeText={(text) => this.setState({text})}
/>
<Text style={{padding: 10, fontSize: 42}}>
{this.state.text.split(' ').map((word) => word && '🍕🍕🍕🍕🍕').join(' ')}
</Text>
</View>
);
}
}
在上面的例子里,我們把text保存到 state 中,因為它會隨着時間變化。
TextInput 可能是天然具有“動態狀態”的最簡單的組件了。
TextInput是一個允許用戶在應用中通過鍵盤輸入文本的基本組件。
本組件的屬性提供了多種特性的配置,譬如自動完成、自動大小寫、占位文字,
以及多種不同的鍵盤類型(如純數字鍵盤)等等。
最簡單的用法就是丟一個TextInput到應用里,然后訂閱它的onChangeText事件來讀取用戶的輸入。
注意,從TextInput里取值這就是目前唯一的做法!也就是使用在onChangeText中用setState把
用戶的輸入寫入到state中,然后在需要取值的地方從this.state中取出值。
它還有一些其它的事件,譬如onSubmitEditing和onFocus。一個簡單的例子如下:

import React, { Component } from 'react';
import { TextInput } from 'react-native';
export default class UselessTextInput extends Component {
constructor(props){
super(props);
this.state = { text:'請輸入任意字符'}
}
render() {
return (
<TextInput
style={{height: 40,borderColor:'gray', borderWidth: 1}}
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
)
}
}
注意有些屬性僅在multiline為true或者為false的時候有效。此外,當multiline=false時,
為元素的某一個邊添加邊框樣式(例如:borderBottomColor,borderLeftWidth等)將不會生效。
為了能夠實現效果你可以使用一個View來包裹TextInput:

import React, { Component } from 'react';
import { TextInput } from 'react-native';
export default class UselessTextInput extends Component {
constructor(props) {
super(props);
this.state = { text: 'Useless Placeholder' };
}
render() {
return (
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
);
}
}
下面的這些,窩還沒有遇到過:
TextInput在安卓上默認有一個底邊框,同時會有一些padding。如果要想使其看起來和iOS上盡量一致,則需要設置padding: 0。
又又,在安卓上長按選擇文本會導致windowSoftInputMode設置變為adjustResize,這樣可能導致絕對定位的元素被鍵盤給頂起來。
要解決這一問題你需要在AndroidManifest.xml中明確指定合適的windowSoftInputMode
( https://developer.android.com/guide/topics/manifest/activity-element.html )值,
或是自己監聽事件來處理布局變化。
更多屬性,見下面鏈接:https://reactnative.cn/docs/textinput/#allowfontscaling
