基本用法
Text組件是React Native中的一個重要組件,相當於iOS中的UILabel和Android中的TextView。Text組件用來存放文本數據。下面是一個簡單的例子:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native'
var PerfectProject = React.createClass({
render: function () {
return (
<Text style={styles.outerText}>I am learning React Native!
<Text style={styles.innerText}>Please study hard!</Text>
</Text>
);
},
});
var styles = StyleSheet.create({
outerText: {
margin: 40,
textAlign: 'center',
color: 'red',
fontSize: 28,
fontFamily: 'Cochin'
},
innerText: {
color: 'green',
fontWeight: 'bold',
},
});
AppRegistry.registerComponent('PerfectProject', () => PerfectProject);
運行效果如下圖所示:

【注意】:這里使用了Text組件的一個特性:嵌套,子Text中可以繼承父Text中的屬性和樣式,但是這種特性遵循就近原則,即如果子Text中有部分屬性或樣式和父Text中的屬性或樣式沖突,則結果顯示為子Text中的屬性或樣式。
屬性
numberOfLines:設置Text組件顯示文本的行數,如果文本行數超過設置的值,則多余的部分將不會顯示。
Style
| 名稱 | 作用 | Value |
|---|---|---|
| color | 字體顏色 | 值的形式有多種 |
| fontFamily | 字體名稱 | 自行查看相關字體 |
| fontSize | 字體大小 | 值為 數字 |
| fontStyle | 字體風格 | enum(‘normal’,’italic’) |
| fontWeight | 字體粗細權重 | enum(‘normal’,’bold’,’100’,’200’,’300’,’400’,’500’,’600’,’700’,’800’,’900’),指定字體粗細,normal和bold適用於大多數字體,不是所有的字體的值都能用數字值,在這種情況下,最接近的值被選擇。 |
| lineHeight | 行高 | 數字(number) |
| textAlign | 文本對齊方法 | enum(‘auto’,’left’,’right’,’center’,’justify’) 指定文本對齊方式,‘justify’值只支持iOS,在Android上會自動回退到left。 |
| textDecorationLine | 橫線位置 | enum(‘none’, ‘underline’, ‘line-through’, ‘underline line-through’) |
| textShadowColor | 陰影效果顏色 | 值的形式有多種 |
| textShadowOffset | 設置陰影效果 | {width:number,height:number} |
| textShadowRadius | 陰影效果圓角 | 數字(number) |
| textAlignVertical | 文本垂直對齊方式 | enum(‘auto’,’top’,’bottom’,’center’) 不支持iOS,只支持Android |
| letterSpacing | 字符間距 | 數字(number)只支持iOS,不支持Android |
| textDecorationColor | 值的形式有多種,color只支持iOS,不支持Android | |
| textDecorationStyle | 橫線的風格 | enum(‘solid’,’double’,’dotted’,’dashed’)只支持iOS,不支持Android |
| writingDirection | 文本方向 | enum(‘auto’,’ltr’,’rtl’)只支持iOS,不支持Android |
