Skip to main content

Text

用于显示文本的 React 组件。

¥A React component for displaying text.

Text 支持嵌套、样式和触摸处理。

¥Text supports nesting, styling, and touch handling.

在以下示例中,嵌套标题和正文文本将从 styles.baseText 继承 fontFamily,但标题提供自己的附加样式。由于字面量换行符,标题和正文将彼此堆叠:

¥In the following example, the nested title and body text will inherit the fontFamily from styles.baseText, but the title provides its own additional styles. The title and body will stack on top of each other on account of the literal newlines:

嵌套文本

¥Nested text

Android 和 iOS 都允许你通过使用特定格式(例如粗体或彩色文本)注释字符串范围来显示格式化文本(iOS 上为 NSAttributedString,Android 上为 SpannableString)。实际上,这是非常乏味的。对于 React Native,我们决定使用 Web 范例,你可以嵌套文本以达到相同的效果。

¥Both Android and iOS allow you to display formatted text by annotating ranges of a string with specific formatting like bold or colored text (NSAttributedString on iOS, SpannableString on Android). In practice, this is very tedious. For React Native, we decided to use web paradigm for this where you can nest text to achieve the same effect.

在幕后,React Native 会将其转换为包含以下信息的扁平 NSAttributedStringSpannableString

¥Behind the scenes, React Native converts this to a flat NSAttributedString or SpannableString that contains the following information:

"I am bold and red"
0-9: bold
9-17: bold, red

容器

¥Containers

<Text> 元素相对于布局是唯一的:里面的一切不再使用 Flexbox 布局而是使用文本布局。这意味着 <Text> 内部的元素不再是矩形,而是在看到行尾时换行。

¥The <Text> element is unique relative to layout: everything inside is no longer using the Flexbox layout but using text layout. This means that elements inside of a <Text> are no longer rectangles, but wrap when they see the end of the line.

<Text>
<Text>First part and </Text>
<Text>second part</Text>
</Text>
// Text container: the text will be inline if the space allowed 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|

有限的样式继承

¥Limited Style Inheritance

在网络上,为整个文档设置字体系列和大小的常用方法是利用继承的 CSS 属性,如下所示:

¥On the web, the usual way to set a font family and size for the entire document is to take advantage of inherited CSS properties like so:

html {
font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;
font-size: 11px;
color: #141823;
}

文档中的所有元素都将继承此字体,除非它们或它们的父元素之一指定了新规则。

¥All elements in the document will inherit this font unless they or one of their parents specifies a new rule.

在 React Native 中,我们对此更加严格:你必须将所有文本节点封装在 <Text> 组件内。文本节点不能直接位于 <View> 下。

¥In React Native, we are more strict about it: you must wrap all the text nodes inside of a <Text> component. You cannot have a text node directly under a <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

¥You also lose the ability to set up a default font for an entire subtree. Meanwhile, fontFamily only accepts a single font name, which is different from font-family in CSS. The recommended way to use consistent fonts and sizes across your application is to create a component MyAppText that includes them and use this component across your app. You can also use this component to make more specific components like MyAppHeaderText for other kinds of text.

<View>
<MyAppText>
Text styled with the default font for the entire application
</MyAppText>
<MyAppHeaderText>Text styled as a header</MyAppHeaderText>
</View>

假设 MyAppText 是一个仅将其子组件渲染为带有样式的 Text 组件的组件,那么 MyAppHeaderText 可以定义如下:

¥Assuming that MyAppText is a component that only renders out its children into a Text component with styling, then MyAppHeaderText can be defined as follows:

const MyAppHeaderText = ({children}) => {
return (
<MyAppText>
<Text style={{fontSize: 20}}>{children}</Text>
</MyAppText>
);
};

以这种方式组合 MyAppText 确保我们从顶层组件获取样式,但让我们能够在特定用例中添加/覆盖它们。

¥Composing MyAppText in this way ensures that we get the styles from a top-level component, but leaves us the ability to add / override them in specific use cases.

React Native 仍然有样式继承的概念,但仅限于文本子树。在这种情况下,第二部分将是粗体和红色的。

¥React Native still has the concept of style inheritance, but limited to text subtrees. In this case, the second part will be both bold and red.

<Text style={{fontWeight: 'bold'}}>
I am bold
<Text style={{color: 'red'}}>and red</Text>
</Text>

我们相信,这种更具约束性的文本样式方式将产生更好的应用:

¥We believe that this more constrained way to style text will yield better apps:

  • (开发商)React 组件在设计时考虑到了强隔离性:你应该能够将组件放置在应用中的任何位置,并相信只要 props 相同,它的外观和行为就会相同。可以从 props 外部继承的文本属性将打破这种隔离。

    ¥(Developer) React components are designed with strong isolation in mind: You should be able to drop a component anywhere in your application, trusting that as long as the props are the same, it will look and behave the same way. Text properties that could inherit from outside of the props would break this isolation.

  • (实现者)React Native 的实现也得到了简化。我们不需要在每个元素上都有 fontFamily 字段,并且每次显示文本节点时都不需要潜在地遍历树直到根。样式继承仅在原生 Text 组件内部进行编码,不会泄漏到其他组件或系统本身。

    ¥(Implementor) The implementation of React Native is also simplified. We do not need to have a fontFamily field on every single element, and we do not need to potentially traverse the tree up to the root every time we display a text node. The style inheritance is only encoded inside of the native Text component and doesn't leak to other components or the system itself.


参考

¥Reference

属性

¥Props

accessibilityHint

可访问性提示可帮助用户了解当可访问性标签中的结果不明确时,他们对可访问性元素执行操作时会发生什么。

¥An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not clear from the accessibility label.

类型
string

accessibilityLanguage
iOS

指示用户与元素交互时屏幕阅读器应使用哪种语言的值。它应该遵循 BCP 47 规范

¥A value indicating which language should be used by the screen reader when the user interacts with the element. It should follow the BCP 47 specification.

请参阅 iOS accessibilityLanguage 文档 了解更多信息。

¥See the iOS accessibilityLanguage doc for more information.

类型
string

accessibilityLabel

当用户与元素交互时覆盖屏幕阅读器读取的文本。默认情况下,标签是通过遍历所有子节点并累加所有以空格分隔的 Text 节点来构造的。

¥Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the Text nodes separated by space.

类型
string

accessibilityRole

告诉屏幕阅读器将当前关注的元素视为具有特定角色。

¥Tells the screen reader to treat the currently focused on element as having a specific role.

在 iOS 上,这些角色映射到相应的辅助功能特性。图片按钮具有与特性设置为 'image' 和 'button' 相同的功能。请参阅 无障碍指南 了解更多信息。

¥On iOS, these roles map to corresponding Accessibility Traits. Image button has the same functionality as if the trait was set to both 'image' and 'button'. See the Accessibility guide for more information.

在 Android 上,这些角色在 TalkBack 上具有与在 iOS 中的 Voiceover 上添加辅助功能特性类似的功能

¥On Android, these roles have similar functionality on TalkBack as adding Accessibility Traits does on Voiceover in iOS

类型
AccessibilityRole

accessibilityState

告诉屏幕阅读器将当前关注的元素视为处于特定状态。

¥Tells the screen reader to treat the currently focused on element as being in a specific state.

你可以提供一种状态、不提供状态或多种状态。状态必须通过对象传入。前任:{selected: true, disabled: true}

¥You can provide one state, no state, or multiple states. The states must be passed in through an object. Ex: {selected: true, disabled: true}.

类型
AccessibilityState

accessibilityActions

辅助功能操作允许辅助技术以编程方式调用组件的操作。accessibilityActions 属性应包含操作对象的列表。每个操作对象应包含字段名称和标签。

¥Accessibility actions allow an assistive technology to programmatically invoke the actions of a component. The accessibilityActions property should contain a list of action objects. Each action object should contain the field name and label.

请参阅 无障碍指南 了解更多信息。

¥See the Accessibility guide for more information.

类型必需的
array

onAccessibilityAction

当用户执行辅助功能操作时调用。该函数的唯一参数是一个包含要执行的操作名称的事件。

¥Invoked when the user performs the accessibility actions. The only argument to this function is an event containing the name of the action to perform.

请参阅 无障碍指南 了解更多信息。

¥See the Accessibility guide for more information.

类型必需的
function

accessible

当设置为 true 时,表示视图是辅助功能元素。

¥When set to true, indicates that the view is an accessibility element.

请参阅 无障碍指南 了解更多信息。

¥See the Accessibility guide for more information.

类型默认
booleantrue

adjustsFontSizeToFit

指定是否应自动缩小字体以适应给定的样式约束。

¥Specifies whether fonts should be scaled down automatically to fit given style constraints.

类型默认
booleanfalse

allowFontScaling

指定字体是否应缩放以遵循文本大小辅助功能设置。

¥Specifies whether fonts should scale to respect Text Size accessibility settings.

类型默认
booleantrue

android_hyphenationFrequency
Android

设置在 Android API 级别 23+ 上确定断词时使用的自动连字频率。

¥Sets the frequency of automatic hyphenation to use when determining word breaks on Android API Level 23+.

类型默认
enum('none', 'normal','full')'none'

aria-busy

表示正在修改某个元素,并且辅助技术可能需要等到更改完成后再通知用户有关更新的信息。

¥Indicates an element is being modified and that assistive technologies may want to wait until the changes are complete before informing the user about the update.

类型默认
booleanfalse

aria-checked

指示可检查元素的状态。该字段可以采用布尔值或 "mixed" 字符串来表示混合复选框。

¥Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes.

类型默认
布尔值,'mixed'false

aria-disabled

指示该元素可感知但已禁用,因此不可编辑或不可操作。

¥Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

类型默认
booleanfalse

aria-expanded

指示可展开元素当前是展开还是折叠。

¥Indicates whether an expandable element is currently expanded or collapsed.

类型默认
booleanfalse

aria-label

定义一个标记交互元素的字符串值。

¥Defines a string value that labels an interactive element.

类型
string

aria-selected

指示当前是否选择了可选元素。

¥Indicates whether a selectable element is currently selected or not.

类型
boolean

dataDetectorType
Android

确定文本元素中转换为可单击 URL 的数据类型。默认情况下,不检测任何数据类型。

¥Determines the types of data converted to clickable URLs in the text element. By default, no data types are detected.

你只能提供一种类型。

¥You can provide only one type.

类型默认
enum('phoneNumber', 'link', 'email', 'none', 'all')'none'

disabled
Android

出于测试目的指定文本视图的禁用状态。

¥Specifies the disabled state of the text view for testing purposes.

类型默认
boolfalse

dynamicTypeRamp
iOS

在 iOS 上应用于此元素的 动态类型 渐变。

¥The Dynamic Type ramp to apply to this element on iOS.

类型默认
enum('caption2', 'caption1', 'footnote', 'subheadline', 'callout', 'body', 'headline', 'title3', 'title2', 'title1', 'largeTitle')'body'

ellipsizeMode

当设置 numberOfLines 时,此属性定义如何截断文本。numberOfLines 必须与该属性一起设置。

¥When numberOfLines is set, this prop defines how the text will be truncated. numberOfLines must be set in conjunction with this prop.

这可以是以下值之一:

¥This can be one of the following values:

  • head - 显示该行,以便末端适合容器,并且行开头处缺失的文本由省略号字形指示。例如,"...wxyz"

    ¥head - The line is displayed so that the end fits in the container and the missing text at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz"

  • middle - 显示该行,以便开头和结尾适合容器,并且中间缺失的文本由省略号字形指示。"ab...yz"

    ¥middle - The line is displayed so that the beginning and end fit in the container and the missing text in the middle is indicated by an ellipsis glyph. "ab...yz"

  • tail - 显示该行,以便开头适合容器,并且行末尾缺少的文本由省略号字形指示。例如,"A B C D..."

    ¥tail - The line is displayed so that the beginning fits in the container and the missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..."

  • clip - 线条不会超出文本容器的边缘。

    ¥clip - Lines are not drawn past the edge of the text container.

在 Android 上,当 numberOfLines 设置为高于 1 的值时,只有 tail 值才能正常工作。

¥On Android, when numberOfLines is set to a value higher than 1, only tail value will work correctly.

类型默认
enum('head', 'middle', 'tail', 'clip')tail

id

用于从原生代码中定位此视图。优先于 nativeID 属性。

¥Used to locate this view from native code. Has precedence over nativeID prop.

类型
string

maxFontSizeMultiplier

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

¥Specifies the largest possible scale a font can reach when allowFontScaling is enabled. Possible values:

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

    ¥null/undefined: inherit from the parent node or the global default (0)

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

    ¥0: no max, ignore parent/global default

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

    ¥>= 1: sets the maxFontSizeMultiplier of this node to this value

类型默认
numberundefined

minimumFontScale
iOS

指定启用 adjustsFontSizeToFit 时字体可以达到的最小比例。(值 0.01-1.0)。

¥Specifies the smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0).

类型
number

nativeID

用于从原生代码中定位此视图。

¥Used to locate this view from native code.

类型
string

numberOfLines

用于在计算文本布局(包括换行)后用省略号截断文本,以使总行数不超过此数字。将此属性设置为 0 将导致取消设置此值,这意味着不会应用线路限制。

¥Used to truncate the text with an ellipsis after computing the text layout, including line wrapping, such that the total number of lines does not exceed this number. Setting this property to 0 will result in unsetting this value, which means that no lines restriction will be applied.

该属性通常与 ellipsizeMode 一起使用。

¥This prop is commonly used with ellipsizeMode.

类型默认
number0

onLayout

在安装和布局更改时调用。

¥Invoked on mount and on layout changes.

类型
({nativeEvent: LayoutEvent}) => void

onLongPress

长按时调用此函数。

¥This function is called on long press.

类型
({nativeEvent: PressEvent}) => void

onMoveShouldSetResponder

此视图是否想要 "claim" 触摸响应能力?当 View 不是响应者时,每次触摸移动都会调用此方法。

¥Does this view want to "claim" touch responsiveness? This is called for every touch move on the View when it is not the responder.

类型
({nativeEvent: PressEvent}) => boolean

onPress

用户按下时调用的函数,在 onPressOut 之后触发。

¥Function called on user press, triggered after onPressOut.

类型
({nativeEvent: PressEvent}) => void

onPressIn

当触摸发生时,在 onPressOutonPress 之前立即调用。

¥Called immediately when a touch is engaged, before onPressOut and onPress.

类型
({nativeEvent: PressEvent}) => void

onPressOut

释放触摸时调用。

¥Called when a touch is released.

类型
({nativeEvent: PressEvent}) => void

onResponderGrant

视图现在正在响应触摸事件。现在是高亮并向用户展示正在发生的事情的时候了。

¥The View is now responding to touch events. This is the time to highlight and show the user what is happening.

在 Android 上,从此回调返回 true,以防止任何其他原生组件成为响应者,直到该响应者终止。

¥On Android, return true from this callback to prevent any other native components from becoming responder until this responder terminates.

类型
({nativeEvent: PressEvent}) => void | boolean

onResponderMove

用户正在移动手指。

¥The user is moving their finger.

类型
({nativeEvent: PressEvent}) => void

onResponderRelease

在触摸结束时触发。

¥Fired at the end of the touch.

类型
({nativeEvent: PressEvent}) => void

onResponderTerminate

应答器已从 View 上取下。可能会在调用 onResponderTerminationRequest 后被其他视图获取,或者可能会被操作系统在没有询问的情况下获取(例如,发生在 iOS 上的控制中心/通知中心)

¥The responder has been taken from the View. Might be taken by other views after a call to onResponderTerminationRequest, or might be taken by the OS without asking (e.g., happens with control center/ notification center on iOS)

类型
({nativeEvent: PressEvent}) => void

onResponderTerminationRequest

其他一些 View 想要成为响应者,并要求该 View 释放其响应者。返回 true 允许其释放。

¥Some other View wants to become a responder and is asking this View to release its responder. Returning true allows its release.

类型
({nativeEvent: PressEvent}) => boolean

onStartShouldSetResponderCapture

如果父 View 想要阻止子 View 在触摸启动时成为响应者,它应该有一个返回 true 的处理程序。

¥If a parent View wants to prevent a child View from becoming a responder on a touch start, it should have this handler which returns true.

类型
({nativeEvent: PressEvent}) => boolean

onTextLayout

在文本布局更改时调用。

¥Invoked on Text layout change.

类型
(TextLayoutEvent) => 混合

pressRetentionOffset

当滚动视图被禁用时,这定义了在停用按钮之前你的触摸可以离开按钮的距离。停用后,尝试将其移回来,你会看到该按钮再次重新激活!禁用滚动视图时,将其来回移动几次。确保传入常量以减少内存分配。

¥When the scroll view is disabled, this defines how far your touch may move off of the button, before deactivating the button. Once deactivated, try moving it back and you'll see that the button is once again reactivated! Move it back and forth several times while the scroll view is disabled. Ensure you pass in a constant to reduce memory allocations.

类型
矩形,号码

role

role 将组件的用途传达给辅助技术的用户。优先于 accessibilityRole 属性。

¥role communicates the purpose of a component to the user of an assistive technology. Has precedence over the accessibilityRole prop.

类型
角色

selectable

允许用户选择文本,以使用原生复制和粘贴功能。

¥Lets the user select text, to use the native copy and paste functionality.

类型默认
booleanfalse

selectionColor
Android

文本的高亮颜色。

¥The highlight color of the text.

类型
color

style

类型
文本样式视图样式属性

suppressHighlighting
iOS

true 时,按下文本时不会发生视觉变化。默认情况下,按下时灰色椭圆形会高亮文本。

¥When true, no visual change is made when text is pressed down. By default, a gray oval highlights the text on press down.

类型默认
booleanfalse

testID

用于在端到端测试中定位此视图。

¥Used to locate this view in end-to-end tests.

类型
string

textBreakStrategy
Android

在 Android API Level 23+ 上设置文本分隔策略,可能的值为 simplehighQualitybalanced

¥Set text break strategy on Android API Level 23+, possible values are simple, highQuality, balanced.

类型默认
enum('simple', 'highQuality', 'balanced')highQuality

lineBreakStrategyIOS
iOS

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

¥Set line break strategy on iOS 14+. Possible values are none, standard, hangul-word and push-out.

类型默认
enum('none', 'standard', 'hangul-word', 'push-out')'none'

类型定义

¥Type Definitions

TextLayout

TextLayout 对象是 TextLayoutEvent 回调的一部分,包含 Text 线的测量数据。

¥TextLayout object is a part of TextLayoutEvent callback and contains the measurement data for Text line.

示例

¥Example

{
capHeight: 10.496,
ascender: 14.624,
descender: 4,
width: 28.224,
height: 18.624,
xHeight: 6.048,
x: 0,
y: 0
}

属性

¥Properties

名称类型可选的描述
ascendernumber文本布局更改后行上升高度。
capHeightnumber大写字母高于基线的高度。
descendernumber文本布局更改后行下降高度。
heightnumber文本布局更改后的行高。
widthnumber文本布局更改后的线条宽度。
xnumber文本组件内的线 X 坐标。
xHeightnumber基线和线中位数之间的距离(语料库大小)。
ynumber文本组件内的线 Y 坐标。

TextLayoutEvent

由于组件布局更改,回调中返回 TextLayoutEvent 对象。它包含一个名为 lines 的键,其值是一个数组,其中包含与每个渲染的文本行相对应的 TextLayout 对象。

¥TextLayoutEvent object is returned in the callback as a result of a component layout change. It contains a key called lines with a value which is an array containing TextLayout object corresponded to every rendered text line.

示例

¥Example

{
lines: [
TextLayout,
TextLayout,
// ...
];
target: 1127;
}

属性

¥Properties

名称类型可选的描述
linesTextLayout 数组为每个渲染行提供 TextLayout 数据。
targetnumber元素的节点 ID。