文本
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
用于显示文本的 React 组件。
Text 支持嵌套、样式设置和触摸处理。
在以下示例中,嵌套的标题和正文文本将继承 styles.baseText 的 fontFamily,但标题会提供自己的额外样式。由于使用了字面换行符,标题和正文将上下堆叠:
嵌套文本
Android 和 iOS 都支持通过标注字符串特定范围(如粗体或彩色文本)来显示格式化文本(iOS 使用 NSAttributedString,Android 使用 SpannableString)。实际操作中这种方式非常繁琐。在 React Native 中,我们决定采用 Web 的范式,通过嵌套文本来实现相同效果。
在底层实现中,React Native 会将其转换为扁平的 NSAttributedString 或 SpannableString,包含以下信息:
"I am bold and red"
0-9: bold
9-17: bold, red
容器
<Text> 元素在布局方面具有特殊性:其内部所有内容不再使用 Flexbox 布局,而是采用文本布局。这意味着 <Text> 内部的元素不再是矩形块,而是在行尾自动换行。
<Text>
<Text>First part and </Text>
<Text>second part</Text>
</Text>
// Text container: the text will be inline, if the space allows it
// |First part and second part|
// otherwise, the text will flow as if it was one
// |First part |
// |and second |
// |part |
<View>
<Text>First part and </Text>
<Text>second part</Text>
</View>
// View container: each text is its own block
// |First part and|
// |second part |
// otherwise, the text will flow in its own block
// |First part |
// |and |
// |second part|
有限的样式继承
在 Web 开发中,通常通过继承 CSS 属性来设置整个文档的字体家族和大小,例如:
html {
font-family:
'lucida grande', tahoma, verdana, arial, sans-serif;
font-size: 11px;
color: #141823;
}
文档中所有元素都会继承此字体,除非它们或其父元素指定了新规则。
在 React Native 中,我们对此更加严格:必须将所有文本节点包裹在 <Text> 组件内。不能在 <View> 下直接放置文本节点。
// BAD: will raise exception, can't have a text node as child of a <View>
<View>
Some text
</View>
// GOOD
<View>
<Text>
Some text
</Text>
</View>
同时您也无法为整个子树设置默认字体。此外,fontFamily 仅接受单个字体名称,这与 CSS 的 font-family 不同。推荐的做法是创建包含统一字体样式的 MyAppText 组件,并在整个应用中使用它。您还可以基于此组件创建更具体的组件,如用于标题的 MyAppHeaderText。
<View>
<MyAppText>
Text styled with the default font for the entire application
</MyAppText>
<MyAppHeaderText>Text styled as a header</MyAppHeaderText>
</View>
假设 MyAppText 是将子元素渲染为带样式的 Text 组件,那么 MyAppHeaderText 可以这样定义:
const MyAppHeaderText = ({children}) => {
return (
<MyAppText>
<Text style={{fontSize: 20}}>{children}</Text>
</MyAppText>
);
};
这种组合 MyAppText 的方式确保我们从顶层组件获取样式,同时保留在特定场景中添加/覆盖样式的灵活性。
React Native 仍支持样式继承概念,但仅限于文本子树。在此情况下,第二部分文本将同时应用粗体和红色样式:
<Text style={{fontWeight: 'bold'}}>
I am bold
<Text style={{color: 'red'}}>and red</Text>
</Text>
我们相信这种更受约束的文本样式方式能带来更好的应用体验:
-(开发者视角)React 组件设计强调强隔离性:您应该能在应用任意位置放置组件,并确信只要属性相同,其外观和行为就会一致。允许文本属性从外部继承会破坏这种隔离。
-(实现者视角)React Native 的实现也得以简化:无需在每个元素上设置 fontFamily 字段,也无需在每次渲染文本节点时遍历到根节点。样式继承仅封装在原生 Text 组件内部,不会泄漏到其他组件或系统本身。
参考
属性
accessibilityHint
当无障碍标签无法明确操作结果时,无障碍提示可帮助用户理解在无障碍元素上执行操作将产生的效果。
| Type |
|---|
| string |
accessibilityLanguage iOS
该值指示屏幕阅读器在用户与元素交互时应使用的语言,必须遵循 BCP 47 规范。
更多信息请参阅 iOS accessibilityLanguage 文档。
| Type |
|---|
| string |
accessibilityLabel
覆盖屏幕阅读器在用户与元素交互时读取的文本内容。默认情况下,标签会通过遍历所有子元素并拼接所有 Text 节点的文本(以空格分隔)来生成。
| Type |
|---|
| string |
accessibilityRole
告知屏幕阅读器将当前聚焦的元素视为具有特定角色。
在 iOS 上,这些角色会映射到对应的 Accessibility Traits。图片按钮的功能等同于同时设置 'image' 和 'button' 特性。详见辅助功能指南。
在 Android 上,这些角色在 TalkBack 中的功能与 iOS Voiceover 中添加 Accessibility Traits 的效果类似。
accessibilityState
告知屏幕阅读器当前聚焦的元素处于特定状态。
可通过对象传递一个或多个状态(例如 {selected: true, disabled: true}),或不传递任何状态。
accessibilityActions
辅助操作允许辅助技术以编程方式触发组件的操作。accessibilityActions 属性应包含操作对象列表,每个对象需包含 name 和 label 字段。
详见辅助功能指南。
| Type | Required |
|---|---|
| array | No |
onAccessibilityAction
当用户执行辅助操作时触发,该函数接收的唯一参数是包含要执行操作名称的事件对象。
详见辅助功能指南。
| Type | Required |
|---|---|
| function | No |
accessible
设为 true 时表示该视图是一个可访问性元素。
详见辅助功能指南。
| Type | Default |
|---|---|
| boolean | true |
adjustsFontSizeToFit
指定字体是否应自动缩放以适应给定的样式约束。
| Type | Default |
|---|---|
| boolean | false |
allowFontScaling
指定字体是否应随系统文字大小辅助设置进行缩放。
| Type | Default |
|---|---|
| boolean | true |
android_hyphenationFrequency Android
在 Android API Level 23+ 上设置自动断字频率,用于确定单词分隔方式。
| Type | Default |
|---|---|
enum('none', 'normal','full') | 'none' |
aria-busy
表示元素正在更新中,辅助技术可能需要等待变更完成后再通知用户。
| Type | Default |
|---|---|
| boolean | false |
aria-checked
表示可勾选元素的状态。该字段可接受布尔值或 "mixed" 字符串(表示混合状态的复选框)。
| Type | Default |
|---|---|
| boolean, 'mixed' | false |
aria-disabled
表示元素可见但处于禁用状态,因此不可编辑或操作。
| Type | Default |
|---|---|
| boolean | false |
aria-expanded
指示可展开元素当前是展开还是折叠状态。
| Type | Default |
|---|---|
| boolean | false |
aria-label
定义用于标记交互元素的字符串值。
| Type |
|---|
| string |
aria-selected
指示可选元素当前是否被选中。
| Type |
|---|
| boolean |
dataDetectorType Android
决定文本元素中哪些类型的数据会被转换为可点击的 URL。默认不检测任何数据类型。
只能提供一种类型。
| Type | Default |
|---|---|
enum('phoneNumber', 'link', 'email', 'none', 'all') | 'none' |
disabled Android
为测试目的指定文本视图的禁用状态。
| Type | Default |
|---|---|
| bool | false |
dynamicTypeRamp iOS
在 iOS 上应用的 动态类型级别。
| Type | Default |
|---|---|
enum('caption2', 'caption1', 'footnote', 'subheadline', 'callout', 'body', 'headline', 'title3', 'title2', 'title1', 'largeTitle') | 'body' |
ellipsizeMode
当设置 numberOfLines 时,此属性定义文本如何截断。必须与 numberOfLines 配合使用。
可选值如下:
-
head- 行尾显示完整内容,行首缺失文本用省略号表示,如:"...wxyz" -
middle- 行首行尾显示完整内容,中间缺失文本用省略号表示,如:"ab...yz" -
tail- 行首显示完整内容,行尾缺失文本用省略号表示,如:"abcd..." -
clip- 不显示超出文本容器边界的部分
在 Android 平台上,当 numberOfLines 设置的值大于 1 时,只有 tail 截断模式能正常工作。
| Type | Default |
|---|---|
enum('head', 'middle', 'tail', 'clip') | tail |
id
用于在原生代码中定位此视图。优先级高于 nativeID 属性。
| Type |
|---|
| string |
maxFontSizeMultiplier
指定启用 allowFontScaling 时字体可达到的最大缩放比例。可能取值:
-
null/undefined:继承父节点或全局默认值 (0) -
0:无最大值限制,忽略父级/全局默认值 -
>= 1:将此节点的maxFontSizeMultiplier设为该值
| Type | Default |
|---|---|
| number | undefined |
minimumFontScale
指定启用 adjustsFontSizeToFit 时字体可达到的最小缩放比例(取值 0.01-1.0)。
| Type |
|---|
| number |
nativeID
用于在原生代码中定位此视图。
| Type |
|---|
| string |
numberOfLines
用于在计算文本布局(包括自动换行)后,通过省略号截断文本,确保总行数不超过此值。设为 0 表示不限制行数。
此属性通常与 ellipsizeMode 配合使用。
| Type | Default |
|---|---|
| number | 0 |
onLayout
在挂载时和布局变化时触发。
| Type |
|---|
({nativeEvent: LayoutEvent}) => void |
onLongPress
长按时触发的回调函数。
| Type |
|---|
({nativeEvent: PressEvent}) => void |
onMoveShouldSetResponder
该视图是否希望“声明”触摸响应?当View不是响应者时,每次在其上的触摸移动都会触发此回调。
| Type |
|---|
({nativeEvent: PressEvent}) => boolean |
onPress
用户按压时触发的函数,在 onPressOut 之后调用。
| Type |
|---|
({nativeEvent: PressEvent}) => void |
onPressIn
触摸开始瞬间调用,在 onPressOut 和 onPress 之前触发。
| Type |
|---|
({nativeEvent: PressEvent}) => void |
onPressOut
触摸释放时调用。
| Type |
|---|
({nativeEvent: PressEvent}) => void |
onResponderGrant
视图正在响应触摸事件。此时应高亮显示并向用户展示响应状态。
在 Android 上,从此回调返回 true 可阻止其他原生组件在此响应终止前成为响应者。
| Type |
|---|
({nativeEvent: PressEvent}) => void | boolean |
onResponderMove
用户移动手指时触发。
| Type |
|---|
({nativeEvent: PressEvent}) => void |
onResponderRelease
触摸结束时触发。
| Type |
|---|
({nativeEvent: PressEvent}) => void |
onResponderTerminate
View 的响应者身份已被剥夺。可能因 onResponderTerminationRequest 调用后被其他视图获取,也可能被系统直接剥夺(例如 iOS 控制中心/通知中心触发时)。
| Type |
|---|
({nativeEvent: PressEvent}) => void |
onResponderTerminationRequest
当其他 View 请求成为响应者并要求当前 View 释放响应权时触发。返回 true 表示允许释放。
| Type |
|---|
({nativeEvent: PressEvent}) => boolean |
onStartShouldSetResponderCapture
当父 View 想要阻止子 View 在触摸开始时成为响应者时,应使用此处理函数并返回 true。
| Type |
|---|
({nativeEvent: PressEvent}) => boolean |
onTextLayout
文本布局变化时触发。
| Type |
|---|
(TextLayoutEvent) => mixed |
pressRetentionOffset
当滚动视图禁用时,此属性定义触摸点可偏离按钮多远才会使按钮失活。失活后往回移动可重新激活按钮!在滚动视图禁用状态下多次往返移动可验证此效果。建议传递常量以减少内存分配。
| Type |
|---|
| Rect, number |
ref
一个在组件挂载时会被赋予元素节点的 ref 设置器。
请注意,Text 组件并不提供文本节点,这与 Web 上的段落元素 (<p>) 是元素节点而非文本节点的情况相同。文本节点会作为它们的子节点存在。
role
role 向辅助技术用户传达组件的用途,优先级高于 accessibilityRole 属性。
| Type |
|---|
| Role |
selectable
允许用户选择文本以使用原生复制粘贴功能。
| Type | Default |
|---|---|
| boolean | false |
selectionColor Android
文本的高亮颜色。
| Type |
|---|
| color |
style
suppressHighlighting iOS
设为 true 时,文本按下不会产生视觉变化。默认情况下,按下时会显示灰色椭圆高亮。
| Type | Default |
|---|---|
| boolean | false |
testID
用于在端到端测试中定位此视图。
| Type |
|---|
| string |
textBreakStrategy Android
在 Android API 23+ 设置文本断行策略,可选值为 simple、highQuality、balanced。
| Type | Default |
|---|---|
enum('simple', 'highQuality', 'balanced') | highQuality |
lineBreakStrategyIOS iOS
在 iOS 14+ 上设置换行策略。可选值包括 none、standard、hangul-word 和 push-out。
| Type | Default |
|---|---|
enum('none', 'standard', 'hangul-word', 'push-out') | 'none' |
类型定义
TextLayout
TextLayout 对象是 TextLayoutEvent 回调的组成部分,包含 Text 行文本的测量数据。
示例
{
capHeight: 10.496,
ascender: 14.624,
descender: 4,
width: 28.224,
height: 18.624,
xHeight: 6.048,
x: 0,
y: 0
}
属性
| Name | Type | Optional | Description |
|---|---|---|---|
| ascender | number | No | The line ascender height after the text layout changes. |
| capHeight | number | No | Height of capital letter above the baseline. |
| descender | number | No | The line descender height after the text layout changes. |
| height | number | No | Height of the line after the text layout changes. |
| width | number | No | Width of the line after the text layout changes. |
| x | number | No | Line X coordinate inside the Text component. |
| xHeight | number | No | Distance between the baseline and median of the line (corpus size). |
| y | number | No | Line Y coordinate inside the Text component. |
TextLayoutEvent
TextLayoutEvent 对象会在组件布局变更时通过回调返回。该对象包含名为 lines 的键,其值为数组结构,数组元素为对应每个渲染文本行的 TextLayout 对象。
示例
{
lines: [
TextLayout,
TextLayout,
// ...
];
target: 1127;
}
属性
| Name | Type | Optional | Description |
|---|---|---|---|
| lines | array of TextLayouts | No | Provides the TextLayout data for every rendered line. |
| target | number | No | The node id of the element. |