TextInput是一個允許用戶在應(yīng)用中通過鍵盤輸入文本的基本組件烁落。本組件的屬性提供了多種特性的配置萍程,譬如自動完成葫录、自動大小寫、占位文字赶熟,以及多種不同的鍵盤類型(如純數(shù)字鍵盤)等等瑰妄。最簡單的用法就是丟一個TextInput到應(yīng)用里,然后訂閱它的onChangeText事件來讀取用戶的輸入映砖。它還有一些其它的事件间坐,譬如onSubmitEditing和onFocus。一個簡單的例子如下:this.setState({text})}? ? value={this.state.text}? />注意有些屬性僅在multiline為true或者為false的時候有效邑退。此外竹宋,當(dāng)multiline=false時,為元素的某一個邊添加邊框樣式(例如:borderBottomColor地技,borderLeftWidth等)將不會生效蜈七。為了能夠?qū)崿F(xiàn)效果你可以使用一個View來包裹TextInput:截圖屬性autoCapitalize enum('none', 'sentences', 'words', 'characters') 控制TextInput是否要自動將特定字符切換為大寫:characters: 所有的字符。words: 每個單詞的第一個字符乓土。sentences: 每句話的第一個字符(默認(rèn))宪潮。none: 不自動切換任何字符為大寫。autoCorrect bool 如果為false趣苏,會關(guān)閉拼寫自動修正狡相。默認(rèn)值是true。autoFocus bool 如果為true食磕,在componentDidMount后會獲得焦點尽棕。默認(rèn)值為false。blurOnSubmit bool 如果為true彬伦,文本框會在提交的時候失焦滔悉。對于單行輸入框默認(rèn)值為true,多行則為false单绑。注意:對于多行輸入框來說回官,如果將blurOnSubmit設(shè)為true,則在按下回車鍵時就會失去焦點同時觸發(fā)onSubmitEditing事件搂橙,而不會換行歉提。defaultValue string 提供一個文本框中的初始值。當(dāng)用戶開始輸入的時候区转,值就可以改變苔巨。在一些簡單的使用情形下,如果你不想用監(jiān)聽消息然后更新value屬性的方法來保持屬性和狀態(tài)同步的時候废离,就可以用defaultValue來代替侄泽。editable bool 如果為false,文本框是不可編輯的蜻韭。默認(rèn)值為true悼尾。keyboardType enum("default", 'numeric', 'email-address', "ascii-capable", 'numbers-and-punctuation', 'url', 'number-pad', 'phone-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search') 決定彈出的何種軟鍵盤的柿扣,譬如numeric(純數(shù)字鍵盤)。這些值在所有平臺都可用:defaultnumericemail-addressmaxLength number 限制文本框中最多的字符數(shù)诀豁。使用這個屬性而不用JS邏輯去實現(xiàn)窄刘,可以避免閃爍的現(xiàn)象。multiline bool 如果為true舷胜,文本框中可以輸入多行文字。默認(rèn)值為false活翩。onBlur function 當(dāng)文本框失去焦點的時候調(diào)用此回調(diào)函數(shù)烹骨。onChange function 當(dāng)文本框內(nèi)容變化時調(diào)用此回調(diào)函數(shù)。onChangeText function 當(dāng)文本框內(nèi)容變化時調(diào)用此回調(diào)函數(shù)材泄。改變后的文字內(nèi)容會作為參數(shù)傳遞沮焕。onEndEditing function 當(dāng)文本輸入結(jié)束后調(diào)用此回調(diào)函數(shù)。onFocus function 當(dāng)文本框獲得焦點的時候調(diào)用此回調(diào)函數(shù)拉宗。onLayout function 當(dāng)組件掛載或者布局變化的時候調(diào)用峦树,參數(shù)為{x, y, width, height}。onSubmitEditing function 此回調(diào)函數(shù)當(dāng)軟鍵盤的確定/提交按鈕被按下的時候調(diào)用此函數(shù)旦事。如果multiline={true}魁巩,此屬性不可用。placeholder string 如果沒有任何文字輸入姐浮,會顯示此字符串谷遂。placeholderTextColor string 占位字符串顯示的文字顏色。secureTextEntry bool 如果為true卖鲤,文本框會遮住之前輸入的文字肾扰,這樣類似密碼之類的敏感文字可以更加安全。默認(rèn)值為false蛋逾。selectTextOnFocus bool 如果為true集晚,當(dāng)獲得焦點的時候,所有的文字都會被選中区匣。selectionColor string 設(shè)置輸入框高亮?xí)r的顏色(在iOS上還包括光標(biāo))style Text#style 譯注:這意味著本組件繼承了所有Text的樣式偷拔。value string 文本框中的文字內(nèi)容。TextInput是一個受約束的(Controlled)的組件沉颂,意味著如果提供了value屬性条摸,原生值會被強制與value屬性保持一致。在大部分情況下這都工作的很好铸屉,不過有些情況下會導(dǎo)致一些閃爍現(xiàn)象——一個常見的原因就是通過不改變value來阻止用戶進(jìn)行編輯钉蒲。如果你希望阻止用戶輸入,可以考慮設(shè)置editable={false}彻坛;如果你是希望限制輸入的長度顷啼,可以考慮設(shè)置maxLength屬性踏枣,這兩個屬性都不會導(dǎo)致閃爍。iosclearButtonMode enum('never', 'while-editing', 'unless-editing', 'always') 是否要在文本框右側(cè)顯示“清除”按鈕钙蒙。iosclearTextOnFocus bool 如果為true茵瀑,每次開始輸入的時候都會清除文本框的內(nèi)容。iosenablesReturnKeyAutomatically bool 如果為true躬厌,鍵盤會在文本框內(nèi)沒有文字的時候禁用確認(rèn)按鈕马昨。默認(rèn)值為false。ioskeyboardAppearance enum('default', 'light', 'dark') 指定鍵盤的顏色扛施。iosonKeyPress function 當(dāng)一個鍵被按下的時候調(diào)用此回調(diào)鸿捧。被按下的鍵會作為參數(shù)傳遞給回調(diào)函數(shù)。會在onChange之前調(diào)用疙渣。iosreturnKeyType enum('default', 'go', 'google', 'join', 'next', 'route', 'search', 'send', 'yahoo', 'done', 'emergency-call') 決定“確定”按鈕顯示的內(nèi)容匙奴。iosselectionState DocumentSelectionState 參見DocumentSelectionState.js,可以控制一個文檔中哪段文字被選中的狀態(tài)妄荔。androidnumberOfLines number 設(shè)置輸入框的行數(shù)泼菌。當(dāng)multiline設(shè)置為true時使用它,可以占據(jù)對應(yīng)的行數(shù)啦租。androidunderlineColorAndroid string 文本框的下劃線顏色(譯注:如果要去掉文本框的邊框哗伯,請將此屬性設(shè)為透明transparent)。方法isFocused(): boolean 返回值表明當(dāng)前輸入框是否獲得了焦點刷钢。clear() 清空輸入框的內(nèi)容笋颤。例子iOS'use strict';var React = require('react');var ReactNative = require('react-native');var {? Text,? TextInput,? View,? StyleSheet,} = ReactNative;var WithLabel = React.createClass({? render: function() {? ? return ({this.props.label}{this.props.children});? },});var TextEventsExample = React.createClass({? getInitialState: function() {? ? return {? ? ? curText: '',? ? ? prevText: '',? ? ? prev2Text: '',? ? ? prev3Text: '',? ? };? },? updateText: function(text) {? ? this.setState((state) => {? ? ? return {? ? ? ? curText: text,? ? ? ? prevText: state.curText,? ? ? ? prev2Text: state.prevText,? ? ? ? prev3Text: state.prev2Text,? ? ? };? ? });? },? render: function() {? ? return (this.updateText('onFocus')}? ? ? ? ? onBlur={() => this.updateText('onBlur')}? ? ? ? ? onChange={(event) => this.updateText(? ? ? ? ? ? 'onChange text: ' + event.nativeEvent.text? ? ? ? ? )}? ? ? ? ? onEndEditing={(event) => this.updateText(? ? ? ? ? ? 'onEndEditing text: ' + event.nativeEvent.text? ? ? ? ? )}? ? ? ? ? onSubmitEditing={(event) => this.updateText(? ? ? ? ? ? 'onSubmitEditing text: ' + event.nativeEvent.text? ? ? ? ? )}? ? ? ? ? onSelectionChange={(event) => this.updateText(? ? ? ? ? ? 'onSelectionChange range: ' +? ? ? ? ? ? ? event.nativeEvent.selection.start + ',' +? ? ? ? ? ? ? event.nativeEvent.selection.end? ? ? ? ? )}? ? ? ? ? onKeyPress={(event) => {? ? ? ? ? ? this.updateText('onKeyPress key: ' + event.nativeEvent.key);? ? ? ? ? }}? ? ? ? ? style={styles.default}? ? ? ? />{this.state.curText}{'\n'}
(prev: {this.state.prevText}){'\n'}
(prev2: {this.state.prev2Text}){'\n'}
(prev3: {this.state.prev3Text}));? }});class AutoExpandingTextInput extends React.Component {? state: any;? constructor(props) {? ? super(props);? ? this.state = {text: '', height: 0};? }? render() {? ? return ({? ? ? ? ? this.setState({? ? ? ? ? ? text: event.nativeEvent.text,? ? ? ? ? ? height: event.nativeEvent.contentSize.height,? ? ? ? ? });? ? ? ? }}? ? ? ? style={[styles.default, {height: Math.max(35, this.state.height)}]}? ? ? ? value={this.state.text}? ? ? />? ? );? }}class RewriteExample extends React.Component {? state: any;? constructor(props) {? ? super(props);? ? this.state = {text: ''};? }? render() {? ? var limit = 20;? ? var remainder = limit - this.state.text.length;? ? var remainderColor = remainder > 5 ? 'blue' : 'red';? ? return ({? ? ? ? ? ? text = text.replace(/ /g, '_');? ? ? ? ? ? this.setState({text});? ? ? ? ? }}? ? ? ? ? style={styles.default}? ? ? ? ? value={this.state.text}? ? ? ? />{remainder});? }}class RewriteExampleInvalidCharacters extends React.Component {? state: any;? constructor(props) {? ? super(props);? ? this.state = {text: ''};? }? render() {? ? return ({
this.setState({text: text.replace(/\s/g, '')});
}}
style={styles.default}
value={this.state.text}
/>);? }}class TokenizedTextExample extends React.Component {? state: any;? constructor(props) {? ? super(props);? ? this.state = {text: 'Hello #World'};? }? render() {? ? //define delimiter? ? let delimiter = /\s+/;? ? //split string? ? let _text = this.state.text;? ? let token, index, parts = [];? ? while (_text) {? ? ? delimiter.lastIndex = 0;? ? ? token = delimiter.exec(_text);? ? ? if (token === null) {? ? ? ? break;? ? ? }? ? ? index = token.index;? ? ? if (token[0].length === 0) {? ? ? ? index = 1;? ? ? }? ? ? parts.push(_text.substr(0, index));? ? ? parts.push(token[0]);? ? ? index = index + token[0].length;? ? ? _text = _text.slice(index);? ? }? ? parts.push(_text);? ? //highlight hashtags? ? parts = parts.map((text) => {? ? ? if (/^#/.test(text)) {? ? ? ? return{text};? ? ? } else {? ? ? ? return text;? ? ? }? ? });? ? return ({? ? ? ? ? ? this.setState({text});? ? ? ? ? }}>{parts});? }}var BlurOnSubmitExample = React.createClass({? focusNextField(nextField) {? ? this.refs[nextField].focus();? },? render: function() {? ? return (this.focusNextField('2')}? ? ? ? />this.focusNextField('3')}? ? ? ? />this.focusNextField('4')}? ? ? ? />this.focusNextField('5')}? ? ? ? />);? }});var styles = StyleSheet.create({? page: {? ? paddingBottom: 300,? },? default: {? ? height: 26,? ? borderWidth: 0.5,? ? borderColor: '#0f0f0f',? ? flex: 1,? ? fontSize: 13,? ? padding: 4,? },? multiline: {? ? borderWidth: 0.5,? ? borderColor: '#0f0f0f',? ? flex: 1,? ? fontSize: 13,? ? height: 50,? ? padding: 4,? ? marginBottom: 4,? },? multilineWithFontStyles: {? ? color: 'blue',? ? fontWeight: 'bold',? ? fontSize: 18,? ? fontFamily: 'Cochin',? ? height: 60,? },? multilineChild: {? ? width: 50,? ? height: 40,? ? position: 'absolute',? ? right: 5,? ? backgroundColor: 'red',? },? eventLabel: {? ? margin: 3,? ? fontSize: 12,? },? labelContainer: {? ? flexDirection: 'row',? ? marginVertical: 2,? ? flex: 1,? },? label: {? ? width: 115,? ? alignItems: 'flex-end',? ? marginRight: 10,? ? paddingTop: 2,? },? rewriteContainer: {? ? flexDirection: 'row',? ? alignItems: 'center',? },? remainder: {? ? textAlign: 'right',? ? width: 24,? },? hashtag: {? ? color: 'blue',? ? fontWeight: 'bold',? },});exports.displayName = (undefined: ?string);exports.title = '';exports.description = 'Single and multi-line text inputs.';exports.examples = [? {? ? title: 'Auto-focus',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: "Live Re-Write (->? '_') + maxLength",? ? render: function() {? ? ? return;? ? }? },? {? ? title: 'Live Re-Write (no spaces allowed)',? ? render: function() {? ? ? return;? ? }? },? {? ? title: 'Auto-capitalize',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Auto-correct',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Keyboard types',? ? render: function() {? ? ? var keyboardTypes = [? ? ? ? 'default',? ? ? ? 'ascii-capable',? ? ? ? 'numbers-and-punctuation',? ? ? ? 'url',? ? ? ? 'number-pad',? ? ? ? 'phone-pad',? ? ? ? 'name-phone-pad',? ? ? ? 'email-address',? ? ? ? 'decimal-pad',? ? ? ? 'twitter',? ? ? ? 'web-search',? ? ? ? 'numeric',? ? ? ];? ? ? var examples = keyboardTypes.map((type) => {? ? ? ? return ();? ? ? });? ? ? return{examples};? ? }? },? {? ? title: 'Keyboard appearance',? ? render: function() {? ? ? var keyboardAppearance = [? ? ? ? 'default',? ? ? ? 'light',? ? ? ? 'dark',? ? ? ];? ? ? var examples = keyboardAppearance.map((type) => {? ? ? ? return ();? ? ? });? ? ? return{examples};? ? }? },? {? ? title: 'Return key types',? ? render: function() {? ? ? var returnKeyTypes = [? ? ? ? 'default',? ? ? ? 'go',? ? ? ? 'google',? ? ? ? 'join',? ? ? ? 'next',? ? ? ? 'route',? ? ? ? 'search',? ? ? ? 'send',? ? ? ? 'yahoo',? ? ? ? 'done',? ? ? ? 'emergency-call',? ? ? ];? ? ? var examples = returnKeyTypes.map((type) => {? ? ? ? return ();? ? ? });? ? ? return{examples};? ? }? },? {? ? title: 'Enable return key automatically',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Secure text entry',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Event handling',? ? render: function(): ReactElement { return; },? },? {? ? title: 'Colored input text',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Colored highlight/cursor for text input',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Clear button mode',? ? render: function () {? ? ? return ();? ? }? },? {? ? title: 'Clear and select',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Blur on submit',? ? render: function(): ReactElement { return; },? },? {? ? title: 'Multiline blur on submit',? ? render: function() {? ? ? return (alert(event.nativeEvent.text)}
/>);? ? }? },? {? ? title: 'Multiline',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Auto-expanding',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Attributed text',? ? render: function() {? ? ? return;? ? }? },];Android'use strict';var React = require('react');var ReactNative = require('react-native');var {? Text,? TextInput,? View,? StyleSheet,} = ReactNative;var TextEventsExample = React.createClass({? getInitialState: function() {? ? return {? ? ? curText: '',? ? ? prevText: '',? ? ? prev2Text: '',? ? };? },? updateText: function(text) {? ? this.setState((state) => {? ? ? return {? ? ? ? curText: text,? ? ? ? prevText: state.curText,? ? ? ? prev2Text: state.prevText,? ? ? };? ? });? },? render: function() {? ? return (this.updateText('onFocus')}? ? ? ? ? onBlur={() => this.updateText('onBlur')}? ? ? ? ? onChange={(event) => this.updateText(? ? ? ? ? ? 'onChange text: ' + event.nativeEvent.text? ? ? ? ? )}? ? ? ? ? onEndEditing={(event) => this.updateText(? ? ? ? ? ? 'onEndEditing text: ' + event.nativeEvent.text? ? ? ? ? )}? ? ? ? ? onSubmitEditing={(event) => this.updateText(? ? ? ? ? ? 'onSubmitEditing text: ' + event.nativeEvent.text? ? ? ? ? )}? ? ? ? ? style={styles.singleLine}? ? ? ? />{this.state.curText}{'\n'}
(prev: {this.state.prevText}){'\n'}
(prev2: {this.state.prev2Text}));? }});class AutoExpandingTextInput extends React.Component {? constructor(props) {? ? super(props);? ? this.state = {text: '', height: 0};? }? render() {? ? return ({? ? ? ? ? this.setState({? ? ? ? ? ? text: event.nativeEvent.text,? ? ? ? ? ? height: event.nativeEvent.contentSize.height,? ? ? ? ? });? ? ? ? }}? ? ? ? style={[styles.default, {height: Math.max(35, this.state.height)}]}? ? ? ? value={this.state.text}? ? ? />? ? );? }}class RewriteExample extends React.Component {? constructor(props) {? ? super(props);? ? this.state = {text: ''};? }? render() {? ? var limit = 20;? ? var remainder = limit - this.state.text.length;? ? var remainderColor = remainder > 5 ? 'blue' : 'red';? ? return ({? ? ? ? ? ? text = text.replace(/ /g, '_');? ? ? ? ? ? this.setState({text});? ? ? ? ? }}? ? ? ? ? style={styles.default}? ? ? ? ? value={this.state.text}? ? ? ? />{remainder});? }}class TokenizedTextExample extends React.Component {? constructor(props) {? ? super(props);? ? this.state = {text: 'Hello #World'};? }? render() {? ? //define delimiter? ? let delimiter = /\s+/;? ? //split string? ? let _text = this.state.text;? ? let token, index, parts = [];? ? while (_text) {? ? ? delimiter.lastIndex = 0;? ? ? token = delimiter.exec(_text);? ? ? if (token === null) {? ? ? ? break;? ? ? }? ? ? index = token.index;? ? ? if (token[0].length === 0) {? ? ? ? index = 1;? ? ? }? ? ? parts.push(_text.substr(0, index));? ? ? parts.push(token[0]);? ? ? index = index + token[0].length;? ? ? _text = _text.slice(index);? ? }? ? parts.push(_text);? ? //highlight hashtags? ? parts = parts.map((text) => {? ? ? if (/^#/.test(text)) {? ? ? ? return{text};? ? ? } else {? ? ? ? return text;? ? ? }? ? });? ? return ({? ? ? ? ? ? this.setState({text});? ? ? ? ? }}>{parts});? }}var BlurOnSubmitExample = React.createClass({? focusNextField(nextField) {? ? this.refs[nextField].focus();? },? render: function() {? ? return (this.focusNextField('2')}? ? ? ? />this.focusNextField('3')}? ? ? ? />this.focusNextField('4')}? ? ? ? />this.focusNextField('5')}? ? ? ? />);? }});var styles = StyleSheet.create({? multiline: {? ? height: 60,? ? fontSize: 16,? ? padding: 4,? ? marginBottom: 10,? },? eventLabel: {? ? margin: 3,? ? fontSize: 12,? },? singleLine: {? ? fontSize: 16,? ? padding: 4,? },? singleLineWithHeightTextInput: {? ? height: 30,? },? hashtag: {? ? color: 'blue',? ? fontWeight: 'bold',? },});exports.title = '';exports.description = 'Single and multi-line text inputs.';exports.examples = [? {? ? title: 'Auto-focus',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: "Live Re-Write (->? '_')",? ? render: function() {? ? ? return;? ? }? },? {? ? title: 'Auto-capitalize',? ? render: function() {? ? ? var autoCapitalizeTypes = [? ? ? ? 'none',? ? ? ? 'sentences',? ? ? ? 'words',? ? ? ? 'characters',? ? ? ];? ? ? var examples = autoCapitalizeTypes.map((type) => {? ? ? ? return ();? ? ? });? ? ? return{examples};? ? }? },? {? ? title: 'Auto-correct',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Keyboard types',? ? render: function() {? ? ? var keyboardTypes = [? ? ? ? 'default',? ? ? ? 'email-address',? ? ? ? 'numeric',? ? ? ? 'phone-pad',? ? ? ];? ? ? var examples = keyboardTypes.map((type) => {? ? ? ? return ();? ? ? });? ? ? return{examples};? ? }? },? {? ? title: 'Blur on submit',? ? render: function(): ReactElement { return; },? },? {? ? title: 'Event handling',? ? render: function(): ReactElement { return; },? },? {? ? title: 'Colors and text inputs',? ? render: function() {? ? ? return (Darker backgroundColor);? ? }? },? {? ? title: 'Text input, themes and heights',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'fontFamily, fontWeight and fontStyle',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Passwords',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Editable',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Multiline',? ? render: function() {? ? ? return (multiline with children, aligned bottom-right);? ? }? },? {? ? title: 'Fixed number of lines',? ? platform: 'android',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Auto-expanding',? ? render: function() {? ? ? return ();? ? }? },? {? ? title: 'Attributed text',? ? render: function() {? ? ? return;? ? }? },? {? ? title: 'Return key',? ? render: function() {? ? ? var returnKeyTypes = [? ? ? ? 'none',? ? ? ? 'go',? ? ? ? 'search',? ? ? ? 'send',? ? ? ? 'done',? ? ? ? 'previous',? ? ? ? 'next',? ? ? ];? ? ? var returnKeyLabels = [? ? ? ? 'Compile',? ? ? ? 'React Native',? ? ? ];? ? ? var examples = returnKeyTypes.map((type) => {? ? ? ? return ();? ? ? });? ? ? var types = returnKeyLabels.map((type) => {? ? ? ? return ();? ? ? });? ? ? return{examples}{types};? ? }? },];