跳到主要内容
新架构实战课 实操 + 基建 + 原理全维度包揽,抢先掌握 React Native 新架构精髓 立即查看 >

TextInput

TextInput 是一个允许用户在应用中通过键盘输入文本的基本组件。本组件的属性提供了多种特性的配置,譬如自动完成、自动大小写、占位文字,以及多种不同的键盘类型(如纯数字键盘)等等。

最简单的用法就是丢一个TextInput到应用里,然后订阅它的onChangeText事件来读取用户的输入。注意,从 TextInput 里取值这就是目前唯一的做法!也就是使用在onChangeText中用setState把用户的输入写入到 state 中,然后在需要取值的地方从 this.state 中取出值。它还有一些其它的事件,譬如onSubmitEditingonFocus。一个简单的例子如下:

Two methods exposed via the native element are .focus() and .blur() that will focus or blur the TextInput programmatically.

注意有些属性仅在multiline为 true 或者为 false 的时候有效。此外,当multiline=false时,为元素的某一个边添加边框样式(例如:borderBottomColorborderLeftWidth等)将不会生效。为了能够实现效果你可以使用一个View来包裹TextInput

TextInput在安卓上默认有一个底边框,同时会有一些 padding。如果要想使其看起来和 iOS 上尽量一致,则需要设置padding: 0

又又,在安卓上长按选择文本会导致windowSoftInputMode设置变为adjustResize,这样可能导致绝对定位的元素被键盘给顶起来。要解决这一问题你需要在 AndroidManifest.xml 中明确指定合适的windowSoftInputMode(https://developer.android.com/guide/topics/manifest/activity-element.html)值,或是自己监听事件来处理布局变化。


Reference

Props

allowFontScaling

控制字体是否要根据系统的“字体大小”辅助选项来进行缩放。默认值为true

类型必需
boolNo

autoCapitalize

控制 TextInput 是否要自动将特定字符切换为大写,This property is not supported by some keyboard types such as name-phone-pad.

  • characters: 所有的字符。
  • words: 每个单词的第一个字符。
  • sentences: 每句话的第一个字符(默认)。
  • none: 不切换。
类型必需
enum('none', 'sentences', 'words', 'characters')No

autoComplete

Specifies autocomplete hints for the system, so it can provide autofill. On Android, the system will aways attempt to offer autofill by using heuristics to identify the type of content. To disable autocomplete, set autoComplete to off.

Possible values for autoComplete are:

  • off
  • username
  • password
  • email
  • name
  • tel
  • street-address
  • postal-code
  • cc-number
  • cc-csc
  • cc-exp
  • cc-exp-month
  • cc-exp-year
类型必需平台
enum('off', 'username', 'password', 'email', 'name', 'tel', 'street-address', 'postal-code', 'cc-number', 'cc-csc', 'cc-exp', 'cc-exp-month', 'cc-exp-year')Android

autoCorrect

如果为 false,会关闭拼写自动修正。默认值是 true。

类型必需
boolNo

autoFocus

如果为 true,在componentDidMount后会获得焦点。默认值为 false。

类型必需
boolNo

blurOnSubmit

如果为 true,文本框会在提交的时候失焦。对于单行输入框默认值为 true,多行则为 false。注意:对于多行输入框来说,如果将blurOnSubmit设为 true,则在按下回车键时就会失去焦点同时触发onSubmitEditing事件,而不会换行。

类型必需
boolNo

caretHidden

如果为 true,则隐藏光标。默认值为 false。

类型必需
boolNo

clearButtonMode

是否要在文本框右侧显示“清除”按钮。仅在单行模式下可用。默认值为never

类型必需平台
enum('never', 'while-editing', 'unless-editing', 'always')NoiOS

clearTextOnFocus

如果为 true,每次开始输入的时候都会清除文本框的内容。

类型必需平台
boolNoiOS

contextMenuHidden

If true, context menu is hidden. The default value is false.

类型必需
boolNo

dataDetectorTypes

设置 text input 内能被转化为可点击 URL 的数据的类型。当且仅当multiline={true}editable={false}时起作用。默认情况下不检测任何数据类型。

可接受一个类型值或类型值数组。

dataDetectorTypes的可用值有:

  • 'phoneNumber'
  • 'link'
  • 'address'
  • 'calendarEvent'
  • 'none'
  • 'all'
类型必需平台
enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all'), ,array of enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all')NoiOS

defaultValue

提供一个文本框中的初始值。当用户开始输入的时候,值就可以改变。在一些简单的使用情形下,如果你不想用监听消息然后更新 value 属性的方法来保持属性和状态同步的时候,就可以用 defaultValue 来代替。

类型必需
stringNo

cursorColor
Android

When provided it will set the color of the cursor (or "caret") in the component. Unlike the behavior of selectionColor the cursor color will be set independently from the color of the text selection box.

类型
color

disableFullscreenUI

当值为 false 时, 如果 text input 的周围有少量可用空间的话(比如说,当手机横过来时),操作系统可能会将这个 text input 设置为全屏模式。当值为 true 时, 这个特性不可用,text input 就是普通的模式。默认为 false。

类型必需平台
boolNoAndroid

editable

如果为 false,文本框是不可编辑的。默认值为 true。

类型必需
boolNo

enablesReturnKeyAutomatically

如果为 true,键盘会在文本框内没有文字的时候禁用确认按钮。默认值为 false。

类型必需平台
boolNoiOS

importantForAutofill

Say the system whether the individual fields in your app should be included in a view structure for autofill purposes on Android API Level 26+, possible values are auto, no, noExcludeDescendants, yes, yesExcludeDescendants. The default value is auto.

  • auto: Let the Android System use its heuristics to determine if the view is important for autofill.
  • no: This view isn't important for autofill.
  • noExcludeDescendants: This view and its children aren't important for autofill.
  • yes: This view is important for autofill.
  • yesExcludeDescendants: This view is important for autofill, but its children aren't important for autofill.
类型Required平台
enum('auto', 'no', 'noExcludeDescendants', 'yes', 'yesExcludeDescendants')NoAndroid

inlineImageLeft

指定一个图片放置在左侧。图片必须放置在/android/app/src/main/res/drawable目录下,经过编译后按如下形式引用(无路径无后缀):

<TextInput
inlineImageLeft='search_icon'
/>
类型必需平台
stringNoAndroid

inlineImagePadding

给放置在左侧的图片设置 padding 样式。

类型必需平台
numberNoAndroid

keyboardAppearance

指定键盘的颜色。

类型必需平台
enum('default', 'light', 'dark')NoiOS

keyboardType

决定弹出何种软键盘类型,譬如numeric(纯数字键盘)。

See screenshots of all the types here.

这些值在所有平台都可用:

  • default
  • number-pad
  • decimal-pad
  • numeric
  • email-address
  • phone-pad

下面的值仅 iOS 可用:

  • ascii-capable
  • numbers-and-punctuation
  • url
  • name-phone-pad
  • twitter
  • web-search

下面的值仅 Android 可用:

  • visible-password
类型必需
enum('default', 'email-address', 'numeric', 'phone-pad', 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search', 'visible-password')No

maxLength

限制文本框中最多的字符数。使用这个属性而不用 JS 逻辑去实现,可以避免闪烁的现象。

类型必需
numberNo

multiline

如果为 true,文本框中可以输入多行文字。默认值为 false。注意安卓上如果设置multiline = {true},文本默认会垂直居中,可设置textAlignVertical: 'top'样式来使其居顶显示。

类型必需
boolNo

numberOfLines

设置输入框的行数。当 multiline 设置为 true 时使用它,可以占据对应的行数。

类型必需平台
numberNoAndroid

onBlur

当文本框失去焦点的时候调用此回调函数。

类型必需
functionNo

onChange

当文本框内容变化时调用此回调函数。回调参数为{ nativeEvent: { eventCount, target, text} }

类型必需
functionNo

onChangeText

当文本框内容变化时调用此回调函数。改变后的文字内容会作为参数传递。

类型必需
functionNo

onContentSizeChange

Callback that is called when the text input's content size changes. This will be called with { nativeEvent: { contentSize: { width, height } } }.

Only called for multiline text inputs.

类型必需
functionNo

onEndEditing

当文本输入结束后调用此回调函数。

类型必需
functionNo

onFocus

当文本框获得焦点的时候调用此回调函数。回调参数为{ nativeEvent: { target } }

类型必需
functionNo

onKeyPress

当一个键被按下的时候调用此回调。传递给回调函数的参数为{ nativeEvent: { key: keyValue } },其中keyValue即为被按下的键。会在 onChange 之前调用。注意:在 Android 上只有软键盘会触发此事件,物理键盘不会触发。

类型必需
functionNo

onLayout

当组件加载或者布局变化的时候调用,回调参数为{ nativeEvent: {layout: {x, y, width, height}, target } }

类型必需
functionNo

onScroll

在内容滚动时持续调用,传回参数的格式形如{ nativeEvent: { contentOffset: { x, y } } }。也可能包含其他和滚动事件相关的参数,但是在 Android 上,出于性能考虑,不会提供contentSize参数。

类型必需
functionNo

onSelectionChange

光标位置变化时,传回参数的格式形如{ nativeEvent: { selection: { start, end } } }

类型必需
functionNo

onSubmitEditing

此回调函数当软键盘的确定/提交按钮被按下的时候调用此函数,所传参数为{nativeEvent: {text, eventCount, target}}。如果multiline={true},此属性不可用。

类型必需
functionNo

Note that on iOS this method isn't called when using keyboardType="phone-pad".


onTextInput

使用光标在某位置输入文本时的回调 { nativeEvent: { text, previousText, range: { start, end } } }

类型Required
functionNo

placeholder

如果没有任何文字输入,会显示此字符串。

类型必需
stringNo

placeholderTextColor

占位字符串显示的文字颜色。

类型必需
colorNo

returnKeyLabel

Sets the return key to the label. Use it instead of returnKeyType.

类型必需平台
stringNoAndroid

returnKeyType

决定“确定”按钮显示的内容。在 Android 上你还可以使用returnKeyLabel

下列这些选项是跨平台可用的:

  • done
  • go
  • next
  • search
  • send

下列这些选项仅 Android 可用:

  • none
  • previous

下列这些选项仅 iOS 可用:

  • default
  • emergency-call
  • google
  • join
  • route
  • yahoo
类型必需
enum('done', 'go', 'next', 'search', 'send', 'none', 'previous', 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo')No

rejectResponderTermination

Determines how the return key should look. On Android you can also use returnKeyLabel.

iOS Only

If true, allows TextInput to pass touch events to the parent component. This allows components such as SwipeableListView to be swipeable from the TextInput on iOS, as is the case on Android by default.

类型Required平台
boolNoiOS

scrollEnabled

If false, scrolling of the text view will be disabled. The default value is true. Only works with multiline={true}.

类型必需平台
booliOS

secureTextEntry

如果为 true,文本框会遮住之前输入的文字,这样类似密码之类的敏感文字可以更加安全。默认值为 false。multiline={true}时不可用。

类型必需
boolNo

selection

设置选中文字的范围(指定首尾的索引值)。如果首尾为同一索引位置,则相当于指定光标的位置。

类型必需
object: {start: number,end: number}No

selectionColor

设置输入框高亮时的颜色(还包括光标)。

类型必需
colorNo

selectTextOnFocus

如果为 true,当获得焦点的时候,所有的文字都会被选中。

类型必需
boolNo

spellCheck

如果设置为false,则禁用拼写检查的样式(比如错误拼写的单词下的红线)。默认值继承自autoCorrect

类型必需平台
boolNoiOS

textAlign

Align the input text to the left, center, or right sides of the input field.

Possible values for textAlign are:

  • left
  • center
  • right
类型Required
enum('left', 'center', 'right')No

textContentType

Give the keyboard and the system information about the expected semantic meaning for the content that users enter.

For iOS 11+ you can set textContentType to username or password to enable autofill of login details from the device keychain.

For iOS 12+ newPassword can be used to indicate a new password input the user may want to save in the keychain, and oneTimeCode can be used to indicate that a field can be autofilled by a code arriving in an SMS.

To disable autofill, set textContentType to none.

Possible values for textContentType are:

  • none
  • URL
  • addressCity
  • addressCityAndState
  • addressState
  • countryName
  • creditCardNumber
  • emailAddress
  • familyName
  • fullStreetAddress
  • givenName
  • jobTitle
  • location
  • middleName
  • name
  • namePrefix
  • nameSuffix
  • nickname
  • organizationName
  • postalCode
  • streetAddressLine1
  • streetAddressLine2
  • sublocality
  • telephoneNumber
  • username
  • password
  • newPassword
  • oneTimeCode
类型必需平台
enum('none', 'URL', 'addressCity', 'addressCityAndState', 'addressState', 'countryName', 'creditCardNumber', 'emailAddress', 'familyName', 'fullStreetAddress', 'givenName', 'jobTitle', 'location', 'middleName', 'name', 'namePrefix', 'nameSuffix', 'nickname', 'organizationName', 'postalCode', 'streetAddressLine1', 'streetAddressLine2', 'sublocality', 'telephoneNumber', 'username', 'password')iOS

passwordRules

When using textContentType as newPassword on iOS we can let the OS know the minimum requirements of the password so that it can generate one that will satisfy them. In order to create a valid string for PasswordRules take a look to the Apple Docs.

类型Required平台
stringNoiOS

style

Note that not all Text styles are supported, an incomplete list of what is not supported includes:

  • borderLeftWidth
  • borderTopWidth
  • borderRightWidth
  • borderBottomWidth
  • borderTopLeftRadius
  • borderTopRightRadius
  • borderBottomRightRadius
  • borderBottomLeftRadius

see Issue#7070 for more detail.

Styles

类型必需
TextNo

textBreakStrategy

在 Android API Level 23+ 的平台上设置文字断行策略, 可能值有simple, highQuality, balanced。默认值为simple

类型必需平台
enum('simple', 'highQuality', 'balanced')NoAndroid

underlineColorAndroid

文本框的下划线颜色(译注:如果要去掉文本框的边框,请将此属性设为透明 transparent)。

类型必需平台
colorNoAndroid

value

文本框中的文字内容。 TextInput 是一个受约束的(Controlled)的组件,意味着如果提供了 value 属性,原生值会被强制与 value 属性保持一致。在大部分情况下这都工作的很好,不过有些情况下会导致一些闪烁现象——一个常见的原因就是通过不改变 value 来阻止用户进行编辑。如果你希望阻止用户输入,可以考虑设置editable={false};如果你是希望限制输入的长度,可以考虑设置maxLength属性,这两个属性都不会导致闪烁。

类型必需
stringNo

方法

.focus()

focus();

Makes the native input request focus.


.blur()

blur();

Makes the native input lose focus.


clear()

clear();

清空输入框的内容。


isFocused()

isFocused();

返回值表明当前输入框是否获得了焦点。