一、簡介
一個用於文本顯示的React組件,並且支持嵌套、樣式以及觸摸處理。
二、Text
在下面的例子里,嵌套的標題和正文文字會繼承來自styles.baseText的fontFamily字體,不過標題上還附加了它自己額外的樣式。標題和文本會在頂部依次堆疊,並且被代碼中內嵌的換行符分隔開。
renderText: function() { return ( <Text style={styles.baseText}> <Text style={styles.titleText} onPress={this.onPressTitle}> {this.state.titleText + '\n\n'} </Text> <Text numberOfLines={5}> {this.state.bodyText} </Text> </Text> ); }, ... var styles = StyleSheet.create({ baseText: { fontFamily: 'Cochin', }, titleText: { fontSize: 20, fontWeight: 'bold', }, };
三、Text的API
-
adjustsFontSizeToFit Boolean 指定字體是否隨着給定樣式的限制而自動縮放
-
allowFontScaling Boolean 控制字體是否要根據系統的“字體大小”輔助選項來進行縮放。
-
minimumFontScale Boolean 當adjustsFontSizeToFit開啟時,指定最小的縮放比(即不能低於這個值)。可設定的值為0.01 - 1.0
-
numberOfLines Number 用來當文本過長的時候裁剪文本。包括折疊產生的換行在內,總的行數不會超過這個屬性的限制。
-
onLayout Function 當掛載或者布局變化以后調用,參數為如下的內容:{nativeEvent: {layout: {x, y, width, height}}}
-
onLongPress Function 當文本被長按以后調用此回調函數。
-
onPress Function 當文本被點擊以后調用此回調函數。
-
selectable 決定用戶是否可以長按選擇文本,以便復制和粘貼。
-
style 自定義樣式
-
- color
- fontFamily
- fontSize
- fontStyle
- fontWeight ->大多數字體都支持normal和bold的值,並非所有字體都支持所有的數值。若不支持賊選擇最接近的值
- lineHeight
- textAlign
- textDecorationLine
- textShadowColor
- textShadowOffset
- textShadowRadius
四、容器
<Text>元素在布局上不同於其他組件:在Text內部的元素不再使用flexbox布局,而采用文本布局。這意味着Text內部的元素不再是一個個矩形,而可能會在行末折疊。
<Text> <Text>First part and </Text> <Text>second part</Text> </Text> // Text container: all the text flows 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|
五、樣式繼承限制
在web上,要想指定整個文檔的字體和大小,我們只需要寫:
/* 這段代碼是CSS, *不是*React Native */ html { font-family: 'lucida grande', tahoma, verdana, arial, sans-serif; font-size: 11px; color: #141823; }
當瀏覽器嘗試渲染一個文本節點的時候,它會在樹中一路向上查詢,直到根節點,來找到一個具備font-size屬性的元素。這個系統一個不好的地方在於任何節點都可能會有font-size屬性,包括<div>標簽。這個設計為了方便而設計,但實際上語義上並不太正確。
在RN中,我們把這個問題設計的更加嚴謹:你必須把你的文本節點放在<Text>組件內,你不能直接在<View>下放置一段文本。
// 錯誤的做法:會導致一個錯誤。<View>下不能直接放一段文本。 <View> 一些文本 </View> // 正確的做法 <View> <Text> 一些文本 </Text> </View>
React Native實際上還是有一部分樣式繼承的實現,不過僅限於文本標簽的子樹。在下面的代碼里,第二部分會在加粗的同時又顯示為紅色:
<Text style={{fontWeight: 'bold'}}>
I am bold
<Text style={{color: 'red'}}>
and red
</Text>
</Text>
