跳到主要内容
版本:0.82

TextInput

通过键盘向应用输入文本的基础组件。Props 提供了多项功能的配置,例如自动纠正、自动大写、占位文本和不同的键盘类型,例如数字键盘。

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

原生元素提供了两个方法:.focus().blur(),可通过编程方式聚焦或取消聚焦 TextInput。

请注意,某些 props 仅在 multiline={true/false} 时可用:

默认情况下,TextInput 的视图底部有一个边框。此边框的内边距由系统提供的背景图片设置,且无法更改。要避免此问题,可以不显式设置高度,此时系统会负责在正确的位置显示边框;或者将 underlineColorAndroid 设置为透明,以不显示边框。

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


参考

Props

View Props

继承 View Props


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,文本字段将在提交时取消聚焦。单行字段的默认值为 true,多行字段的默认值为 false。请注意,对于多行字段,将 blurOnSubmit 设置为 true 意味着按下回车键会使字段取消聚焦,并触发 onSubmitEditing 事件,而不是在字段中插入换行符。

Type
bool

caretHidden

如果为 true,则隐藏光标。默认值为 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

确定文本输入中哪些类型的数据应转换为可点击的 URL。仅当 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

提供一个初始值,该值会在用户开始输入时发生变化。适用于不想处理监听事件并更新 value prop,以保持受控状态同步的场景。

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 prop。

以下值可跨平台使用:

  • done
  • next
  • search
  • send
  • go

仅限 Android

以下值仅可在 Android 上使用:

  • previous

仅限 iOS

以下值仅可在 iOS 上使用:

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

importantForAutofill
Android

告知操作系统,在 Android API Level 26+ 上,应用中的各个字段是否应出现在用于自动填充的视图结构中。可能的值为 autononoExcludeDescendantsyesyesExcludeDescendants。默认值为 auto

  • auto:让 Android System 使用启发式方法确定视图对于自动填充是否重要
  • 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')

lineBreakStrategyIOS
iOS

在 iOS 14+ 上设置换行策略。可能的值为 nonestandardhangul-wordpush-out

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

lineBreakModeIOS
iOS

在 iOS 上设置换行模式。可能的值为 wordWrappingcharclipheadmiddletail

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

maxFontSizeMultiplier

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

  • null/undefined(默认):从父节点或全局默认值(0)继承
  • 0:无最大值,忽略父节点/全局默认值
  • >= 1:将此节点的 maxFontSizeMultiplier 设置为此值
Type
number

maxLength

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

Type
number

multiline

如果为 true,则文本输入可以包含多行。默认值为 false

备注

需要注意的是,在 iOS 上,这会将文本对齐到顶部,而在 Android 上会将其居中。将其与 textAlignVertical 设置为 top 一起使用,可使两个平台的行为一致。

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

将回车键设置为指定标签。请使用它代替 returnKeyType

Type
string

returnKeyType

确定回车键的外观。在 Android 上,也可以使用 returnKeyLabel

跨平台

以下值可跨平台使用:

  • done
  • go
  • next
  • search
  • send

仅限 Android

以下值仅可在 Android 上使用:

  • none
  • previous

仅限 iOS

以下值仅可在 iOS 上使用:

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

rejectResponderTermination
iOS

如果为 true,则允许 TextInput 将触摸事件传递给父组件。这使得 SwipeableListView 等组件可以在 iOS 上从 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

文本输入的选择起点和终点。将 start 和 end 设置为相同的值可以定位光标。

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

selectionColor

文本输入的高亮、选择控件和光标颜色。

Type
color

selectionHandleColor
Android

设置选择控件的颜色。与 selectionColor 不同,它允许独立于选择颜色自定义选择控件颜色。

Type
color

selectTextOnFocus

如果为 true,则在获得焦点时自动选择所有文本。

Type
bool

showSoftInputOnFocus

当为 false 时,会阻止字段获得焦点时显示软键盘。默认值为 true

Type
bool

smartInsertDelete
iOS

如果为 false,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 Docs

提示

如果密码生成对话框没有出现,请确认:

  • AutoFill 已启用:设置密码与账户 → 将 自动填充密码 切换为“开启”
  • 使用了 iCloud Keychain:设置Apple IDiCloud钥匙串 → 将 iCloud 钥匙串 切换为“开启”
Type
string

style

请注意,并非所有 Text 样式都受支持,不受支持的样式包括以下不完整列表:

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

Styles

Type
Text

textBreakStrategy
Android

在 Android API Level 23+ 上设置文本换行策略。可能的值为 simplehighQualitybalanced。默认值为 highQuality

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

underlineColorAndroid
Android

TextInput 下划线的颜色。

Type
color

value

文本输入要显示的值。TextInput 是受控组件,这意味着如果提供了此 value prop,原生值将被强制与该值保持一致。对于大多数用法来说,这非常有效,但在某些情况下可能会导致闪烁——一个常见原因是通过保持 value 不变来阻止编辑。除了设置相同的值之外,还应设置 editable={false},或者设置/更新 maxLength,以防止不需要的编辑且避免闪烁。

Type
string

方法

.focus()

React TSX
focus();

使原生输入请求获得焦点。

.blur()

React TSX
blur();

使原生输入失去焦点。

clear()

React TSX
clear();

删除 TextInput 中的所有文本。


isFocused()

React 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