跳至主内容
版本:0.80

TextInput

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

这是一个基础组件,用于通过键盘在应用中输入文本。通过 props 可配置多项功能,例如自动更正、自动大写、占位文本以及不同的键盘类型(如数字键盘)。

最基本的用法是放置一个 TextInput 并订阅 onChangeText 事件来读取用户输入。还可以订阅其他事件,例如 onSubmitEditingonFocus。以下是一个最小示例:

通过原生元素暴露的两个方法是 .focus().blur(),可用于以编程方式聚焦或失焦 TextInput。

请注意,某些 props 仅在 multiline={true/false} 时可用。此外,如果 multiline=true,则仅作用于元素单侧的边框样式(例如 borderBottomColorborderLeftWidth 等)将不会生效。要实现相同效果,可以将 TextInput 包裹在 View 中:

默认情况下,TextInput 视图底部会显示边框。该边框的内边距由系统提供的背景图像设置,且无法更改。解决方案有两种:要么不显式设置高度(此时系统会自动在正确位置显示边框),要么通过设置 underlineColorAndroid 为透明来隐藏边框。

注意在 Android 上,输入框中的文本选择操作可能将应用的 windowSoftInputMode 参数更改为 adjustResize。这可能导致使用 position: 'absolute' 的组件在键盘激活时出现问题。要避免此行为,可在 AndroidManifest.xml (https://developer.android.com/guide/topics/manifest/activity-element.html) 中指定 windowSoftInputMode,或通过原生代码以编程方式控制该参数。


参考

属性

View 属性

继承 View 属性


allowFontScaling

指定字体是否应缩放以适应文字大小辅助功能设置。默认值为 true

Type
bool

autoCapitalize

控制 TextInput 自动大写特定字符。部分键盘类型(如 name-phone-pad)不支持此属性。

  • characters:全部字符大写

  • words:每个单词首字母大写

  • sentences:每句首字母大写(默认

  • none:不自动大写

Type
enum('none', 'sentences', 'words', 'characters')

autoComplete

为系统指定自动填充提示。在 Android 上,系统总会通过启发式方法尝试提供自动填充。要禁用自动完成,请将 autoComplete 设为 off

以下值全平台通用:

  • additional-name

  • address-line1

  • address-line2

  • birthdate-day (iOS 17+)

  • birthdate-full (iOS 17+)

  • birthdate-month (iOS 17+)

  • birthdate-year (iOS 17+)

  • cc-csc (iOS 17+)

  • cc-exp (iOS 17+)

  • cc-exp-day (iOS 17+)

  • cc-exp-month (iOS 17+)

  • cc-exp-year (iOS 17+)

  • cc-number

  • country

  • current-password

  • email

  • family-name

  • given-name

  • honorific-prefix

  • honorific-suffix

  • name

  • new-password

  • off

  • one-time-code

  • postal-code

  • street-address

  • tel

  • username

iOS

以下值仅 iOS 可用:

  • cc-family-name (iOS 17+)

  • cc-given-name (iOS 17+)

  • cc-middle-name (iOS 17+)

  • cc-name (iOS 17+)

  • cc-type (iOS 17+)

  • nickname

  • organization

  • organization-title

  • url

Android

以下值仅 Android 可用:

  • gender

  • name-family

  • name-given

  • name-middle

  • name-middle-initial

  • name-prefix

  • name-suffix

  • password

  • password-new

  • postal-address

  • postal-address-country

  • postal-address-extended

  • postal-address-extended-postal-code

  • postal-address-locality

  • postal-address-region

  • sms-otp

  • tel-country-code

  • tel-device

  • tel-national

  • username-new

Type
enum('additional-name', 'address-line1', 'address-line2', 'birthdate-day', 'birthdate-full', 'birthdate-month', 'birthdate-year', 'cc-csc', 'cc-exp', 'cc-exp-day', 'cc-exp-month', 'cc-exp-year', 'cc-number', 'country', 'current-password', 'email', 'family-name', 'given-name', 'honorific-prefix', 'honorific-suffix', 'name', 'new-password', 'off', 'one-time-code', 'postal-code', 'street-address', 'tel', 'username', 'cc-family-name', 'cc-given-name', 'cc-middle-name', 'cc-name', 'cc-type', 'nickname', 'organization', 'organization-title', 'url', 'gender', 'name-family', 'name-given', 'name-middle', 'name-middle-initial', 'name-prefix', 'name-suffix', 'password', 'password-new', 'postal-address', 'postal-address-country', 'postal-address-extended', 'postal-address-extended-postal-code', 'postal-address-locality', 'postal-address-region', 'sms-otp', 'tel-country-code', 'tel-device', 'tel-national', 'username-new')

autoCorrect

如果设为 false,则禁用自动更正功能。默认值为 true

Type
bool

autoFocus

如果设为 true,则自动聚焦输入框。默认值为 false

Type
bool

blurOnSubmit

已弃用。 请注意,submitBehavior 现已取代 blurOnSubmit 的功能,并将覆盖 blurOnSubmit 定义的所有行为。详见 submitBehavior

如果设为 true,文本字段在提交时会失去焦点(blur)。对于单行字段,默认值为 true;对于多行字段,默认值为 false。请注意,对于多行字段,将 blurOnSubmit 设置为 true 意味着按下返回键会使字段失去焦点并触发 onSubmitEditing 事件,而不是在字段中插入新行。

Type
bool

caretHidden

如果设为 true,则隐藏光标(caret)。默认值为 false

Type
bool

clearButtonMode
iOS

清除按钮应何时出现在文本框右侧。此属性仅支持单行 TextInput 组件,默认值为 never(从不显示)。

Type
enum('never', 'while-editing', 'unless-editing', 'always')

clearTextOnFocus
iOS

若为 true,在开始编辑时会自动清空文本框内容。

Type
bool

contextMenuHidden

若为 true 则隐藏上下文菜单,默认值为 false

Type
bool

dataDetectorTypes
iOS

决定文本输入中哪些数据类型会被转换为可点击链接。仅在 multiline={true}editable={false} 时生效,默认不检测任何数据类型。

可接受单一类型或类型数组。

dataDetectorTypes 可选值:

  • 'phoneNumber'(电话号码)

  • 'link'(链接)

  • 'address'(地址)

  • 'calendarEvent'(日历事件)

  • 'none'(无)

  • 'all'(全部)

Type
enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all'), ,array of enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all')

defaultValue

提供初始值,该值会在用户开始输入时被替换。适用于不需要通过监听事件来同步受控状态的场景。

Type
string

disableKeyboardShortcuts
iOS

如果为 true,则禁用键盘快捷操作(撤销/重做和复制按钮)。

TypeDefault
boolfalse

cursorColor
Android

设置组件中光标(或"插入符")的颜色。与 selectionColor 不同,此属性可独立于文本选择框颜色单独设置。

Type
color

disableFullscreenUI
Android

当值为 false 时,若文本框周围空间较小(如手机横屏模式),系统可能启用全屏文本编辑模式。设为 true 则始终在文本框内直接编辑,默认值为 false

Type
bool

editable

若为 false 则禁止文本编辑,默认值为 true

Type
bool

enablesReturnKeyAutomatically
iOS

若为 true,无文本时禁用键盘回车键,有文本时自动启用,默认值为 false

Type
bool

enterKeyHint

决定回车键显示的文本,优先级高于 returnKeyType 属性。

以下值全平台通用:

  • done(完成)

  • next(下一个)

  • search

  • send(发送)

  • go(前往)

仅 Android

以下值仅 Android 可用:

  • previous(上一个)

仅 iOS

以下值仅 iOS 可用:

  • enter(进入)
Type
enum('enter', 'done', 'next', 'previous', 'search', 'send', 'go')

importantForAutofill
Android

指示 Android API 26+ 系统中是否将应用内字段纳入自动填充视图结构。可选值:auto(自动)、no(不包含)、noExcludeDescendants(不包含后代元素)、yes(包含)、yesExcludeDescendants(包含后代元素),默认值为 auto

  • auto:由 Android 系统自动判定视图对自动填充的重要性

  • no:此视图对自动填充不重要

  • noExcludeDescendants:此视图及其子视图对自动填充不重要

  • yes:此视图对自动填充重要

  • yesExcludeDescendants:此视图对自动填充重要,但其子视图不重要

Type
enum('auto', 'no', 'noExcludeDescendants', 'yes', 'yesExcludeDescendants')

inlineImageLeft
Android

若定义此属性,指定的图片资源将显示在左侧。图片资源必须位于 /android/app/src/main/res/drawable 目录下,引用方式如下:

<TextInput
inlineImageLeft='search_icon'
/>
Type
string

inlineImagePadding
Android

内联图片(如果存在)与文本输入框本身之间的间距

Type
number

inputAccessoryViewID
iOS

可选标识符,用于将自定义的 InputAccessoryView 关联到此文本输入框。当该输入框获得焦点时,InputAccessoryView 将显示在键盘上方

Type
string

inputAccessoryViewButtonLabel
iOS

可选标签,用于覆盖默认的 InputAccessoryView 按钮标签

默认情况下按钮标签未本地化,使用此属性可提供本地化版本

Type
string

inputMode

功能类似 HTML 中的 inputmode 属性,用于确定打开哪种键盘(例如 numeric),优先级高于 keyboardType

支持以下值:

  • none

  • text

  • decimal

  • numeric

  • tel

  • search

  • email

  • url

Type
enum('decimal', 'email', 'none', 'numeric', 'search', 'tel', 'text', 'url')

keyboardAppearance
iOS

确定键盘颜色

Type
enum('default', 'light', 'dark')

keyboardType

决定打开哪种键盘,例如 numeric

所有键盘类型示例截图可在此查看

以下值全平台通用:

  • default(默认)

  • number-pad

  • decimal-pad

  • numeric

  • email-address

  • phone-pad

  • url

仅 iOS

以下值仅 iOS 可用:

  • ascii-capable

  • numbers-and-punctuation

  • name-phone-pad

  • twitter

  • web-search

仅 Android

以下值仅 Android 可用:

  • visible-password
Type
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')

lineBreakModeIOS
iOS

在 iOS 上设置断行模式,可选值为 wordWrappingcharclipheadmiddletail

TypeDefault
enum('wordWrapping', 'char', 'clip', 'head', 'middle', 'tail')'wordWrapping'

lineBreakStrategyIOS
iOS

在 iOS 14+ 上设置换行策略。可选值包括 nonestandardhangul-wordpush-out

TypeDefault
enum('none', 'standard', 'hangul-word', 'push-out')'none'

maxFontSizeMultiplier

指定启用 allowFontScaling 时字体可达到的最大缩放比例。可能取值:

  • null/undefined(默认):继承父节点或全局默认值(0)

  • 0:无最大值限制,忽略父级/全局默认值

  • >= 1:将此节点的 maxFontSizeMultiplier 设为该值

Type
number

maxLength

限制可输入的最大字符数。使用此属性代替在 JavaScript 中实现逻辑,以避免界面闪烁。

Type
number

multiline

如果设为 true,文本输入框支持多行输入。默认值为 false

备注

需要注意的是:在 iOS 上该属性会使文本顶部对齐,在 Android 上则居中显示。若要在双平台获得一致行为,请同时设置 textAlignVerticaltop

Type
bool

numberOfLines

备注

iOS 平台上的 numberOfLines 仅在新架构中可用

设置 TextInput 的最大行数。需与 multiline 设置为 true 配合使用以实现行填充效果。

Type
number

onBlur

当文本输入框失去焦点时触发的回调函数。

注意:若尝试从 nativeEvent 获取 text 值,请注意返回结果可能为 undefined 导致意外错误。如需获取 TextInput 的最终值,请使用编辑完成后触发的 onEndEditing 事件。

Type
({nativeEvent: TargetEvent}) => void

onChange

当文本输入框内容变化时触发的回调函数。

Type
({nativeEvent: {eventCount, target, text}}) => void

onChangeText

当文本输入框内容变化时触发的回调函数。变更后的文本会以字符串形式作为回调参数传递。

Type
function

onContentSizeChange

当文本输入框内容尺寸变化时触发的回调函数。

仅适用于多行文本输入框。

Type
({nativeEvent: {contentSize: {width, height} }}) => void

onEndEditing

当文本输入结束时触发的回调函数。

Type
function

onPressIn

当触摸事件被激活时触发的回调函数。

Type
({nativeEvent: PressEvent}) => void

onPressOut

当触摸事件被释放时触发的回调函数。

Type
({nativeEvent: PressEvent}) => void

onFocus

当文本输入框获得焦点时触发的回调函数。

Type
({nativeEvent: TargetEvent}) => void

onKeyPress

当按键被按下时触发的回调函数。回调参数对象中:回车键对应 keyValue'Enter',退格键对应 'Backspace',其他按键则返回输入字符(包括空格 ' ')。该回调在 onChange 之前触发。注意:Android 仅处理软键盘输入,不响应物理键盘事件。

Type
({nativeEvent: {key: keyValue} }) => void

onLayout

在挂载时和布局变化时触发。

Type
({nativeEvent: LayoutEvent}) => void

onScroll

在内容滚动时触发。可能包含 ScrollEvent 的其他属性,但 Android 出于性能考虑不提供 contentSize

Type
({nativeEvent: {contentOffset: {x, y} }}) => void

onSelectionChange

当文本输入框选中区域变化时触发的回调函数。

Type
({nativeEvent: {selection: {start, end} }}) => void

onSubmitEditing

当文本输入框提交按钮被按下时触发的回调函数。

Type
({nativeEvent: {text, eventCount, target}}) => void

注意:在 iOS 上使用 keyboardType="phone-pad" 时不会触发此回调。


placeholder

占位文本,在用户输入前显示的字符串。

Type
string

placeholderTextColor

占位符文本的颜色。

Type
color

readOnly

设为 true 时文本不可编辑,默认值为 false

Type
bool

returnKeyLabel
Android

设置回车键的显示标签(Android 专属),可替代 returnKeyType 使用。

Type
string

returnKeyType

决定回车键的显示样式(Android 上也可使用 returnKeyLabel)。

跨平台选项

以下值全平台通用:

  • done(完成)

  • go(前往)

  • next(下一个)

  • search

  • send(发送)

仅 Android

以下值仅 Android 可用:

  • none

  • previous(上一个)

仅 iOS

以下值仅 iOS 可用:

  • default(默认)

  • emergency-call(紧急呼叫)

  • google(Google)

  • join(加入)

  • route(路线)

  • yahoo(雅虎)

Type
enum('done', 'go', 'next', 'search', 'send', 'none', 'previous', 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo')

rejectResponderTermination
iOS

设为 true 时,允许 TextInput 将触摸事件传递给父组件(iOS 专属)。这使得类似 SwipeableListView 的组件可以从 TextInput 区域滑动操作(Android 默认支持此行为)。设为 false 时,TextInput 始终独占输入处理(禁用状态除外)。默认值为 true

Type
bool

rows
Android

设置 TextInput 的行数(需配合 multiline 设置为 true 使用,以便能够填充行)。

Type
number

scrollEnabled
iOS

设为 false 时禁用文本滚动,默认值为 true(仅当 multiline={true} 时生效)。

Type
bool

secureTextEntry

设为 true 时隐藏输入文本(适用于密码等敏感信息),默认值为 false(与 multiline={true} 不兼容)。

Type
bool

selection

设置文本选中区域的起止位置。起止值相同时表示光标定位。

Type
object: {start: number,end: number}

selectionColor

文本输入框的选中高亮色、选择手柄和光标颜色。

Type
color

selectionHandleColor
Android

设置选择手柄的颜色(Android 专属)。与 selectionColor 不同,此属性可独立于选中区域颜色单独设置。

Type
color

selectTextOnFocus

设为 true 时,聚焦时自动全选所有文本。

Type
bool

showSoftInputOnFocus

设为 false 时阻止聚焦时弹出软键盘,默认值为 true

Type
bool

smartInsertDelete
iOS

设为 false 时,iOS 系统在粘贴操作后不会自动添加空格,且在剪切/删除操作后不会自动删除空格(iOS 专属)。

TypeDefault
booltrue

spellCheck
iOS

如果为 false,则禁用拼写检查样式(即红色下划线)。默认值继承自 autoCorrect

Type
bool

submitBehavior

当按下返回键时:

对于单行输入:

  • 'newline' 默认为 'blurAndSubmit'

  • undefined 默认为 'blurAndSubmit'

对于多行输入:

  • 'newline' 会添加换行符

  • undefined 默认为 'newline'

对于单行和多行输入:

  • 'submit' 仅发送提交事件,不会使输入框失焦

  • 'blurAndSubmit'` 会使输入框失焦并发送提交事件

Type
enum('submit', 'blurAndSubmit', 'newline')

textAlign

将输入文本在输入框内左对齐、居中或右对齐。

textAlign 的可能取值有:

  • left

  • center

  • right

Type
enum('left', 'center', 'right')

textContentType
iOS

为键盘和系统提供用户输入内容的预期语义信息。

备注

autoComplete 提供了相同的功能,并且在所有平台上都可用。你可以使用 Platform.select 来处理不同平台的行为。

避免同时使用 textContentTypeautoComplete。为了向后兼容,当两个属性都设置时,textContentType 优先级更高。

可将 textContentType 设为 usernamepassword,以启用设备钥匙串自动填充登录信息。

newPassword 用于表示用户可能想要保存到钥匙串的新密码输入,oneTimeCode 表示可通过短信验证码自动填充的字段。

要禁用自动填充,请将 textContentType 设为 none

textContentType 的可能取值有:

  • none

  • addressCity

  • addressCityAndState

  • addressState

  • birthdate (iOS 17+)

  • birthdateDay (iOS 17+)

  • birthdateMonth (iOS 17+)

  • birthdateYear (iOS 17+)

  • countryName

  • creditCardExpiration (iOS 17+)

  • creditCardExpirationMonth (iOS 17+)

  • creditCardExpirationYear (iOS 17+)

  • creditCardFamilyName (iOS 17+)

  • creditCardGivenName (iOS 17+)

  • creditCardMiddleName (iOS 17+)

  • creditCardName (iOS 17+)

  • creditCardNumber

  • creditCardSecurityCode (iOS 17+)

  • creditCardType (iOS 17+)

  • emailAddress

  • familyName

  • fullStreetAddress

  • givenName

  • jobTitle

  • location

  • middleName

  • name

  • namePrefix

  • nameSuffix

  • newPassword

  • nickname

  • oneTimeCode

  • organizationName

  • password

  • postalCode

  • streetAddressLine1

  • streetAddressLine2

  • sublocality

  • telephoneNumber

  • URL

  • username

Type
enum('none', 'addressCity', 'addressCityAndState', 'addressState', 'birthdate', 'birthdateDay', 'birthdateMonth', 'birthdateYear', 'countryName', 'creditCardExpiration', 'creditCardExpirationMonth', 'creditCardExpirationYear', 'creditCardFamilyName', 'creditCardGivenName', 'creditCardMiddleName', 'creditCardName', 'creditCardNumber', 'creditCardSecurityCode', 'creditCardType', 'emailAddress', 'familyName', 'fullStreetAddress', 'givenName', 'jobTitle', 'location', 'middleName', 'name', 'namePrefix', 'nameSuffix', 'newPassword', 'nickname', 'oneTimeCode', 'organizationName', 'password', 'postalCode', 'streetAddressLine1', 'streetAddressLine2', 'sublocality', 'telephoneNumber', 'URL', 'username')

passwordRules
iOS

在 iOS 上使用 textContentType 设置为 newPassword 时,我们可以让操作系统了解密码的最低要求,使其生成满足条件的密码。要创建有效的 PasswordRules 字符串,请参阅 Apple 文档

如果未出现密码生成对话框,请确保:

  • 已启用自动填充:设置密码与账户 → 开启自动填充密码
  • 已使用 iCloud 钥匙串:设置Apple IDiCloud钥匙串 → 开启iCloud 钥匙串
Type
string

style

请注意并非所有文本样式都受支持,部分不支持样式包括:

  • borderLeftWidth

  • borderTopWidth

  • borderRightWidth

  • borderBottomWidth

  • borderTopLeftRadius

  • borderTopRightRadius

  • borderBottomRightRadius

  • borderBottomLeftRadius

样式

Type
Text

textBreakStrategy
Android

在 Android API 23+ 上设置文本断行策略,可选值为 simplehighQualitybalanced,默认值为 highQuality

Type
enum('simple', 'highQuality', 'balanced')

underlineColorAndroid
Android

TextInput 下划线的颜色。

Type
color

value

文本输入框显示的值。TextInput 是受控组件,这意味着如果提供了此值属性,原生值将强制与其匹配。在大多数情况下效果良好,但有时可能导致闪烁——常见原因是保持值不变来阻止编辑。除了设置相同值外,可以设置 editable={false} 或设置/更新 maxLength 来避免闪烁情况下阻止意外编辑。

Type
string

方法

.focus()

tsx
focus();

使原生输入框获取焦点。

.blur()

tsx
blur();

使原生输入框失去焦点。

clear()

tsx
clear();

移除 TextInput 中的所有文本。


isFocused()

tsx
isFocused(): boolean;

如果输入框当前处于聚焦状态则返回 true;否则返回 false

已知问题

  • react-native#19096:不支持 Android 的 onKeyPreIme

  • react-native#19366:在通过返回键关闭 Android 键盘后调用 .focus() 不会再次唤出键盘。

  • react-native#26799:当 keyboardType="email-address"keyboardType="phone-pad" 时不支持 Android 的 secureTextEntry