Text控件是React Native最常用的幾個控件之一了,因為幾乎沒有哪個應用不使用文案展示功能的。在展示文案時,我們常常需要限定Text顯示區域的寬度,而文本出現超長時,要么選擇截斷,要么選擇換行。當選擇換行時,我們要對換行做出一些響應,比如我們需要因此調整所在容器的高度等。本文就演示一下如何動態檢測Text控件出現了換行。
單個Text,無嵌套的情況
參照以下步驟:
- 設置numberOfLines屬性,指定最大行數
- 設置lineHeight樣式,指定行高
- 設置onLayout屬性,并在回調函數中判斷當前控件的總高度: 1倍的lineHeight為1行,2倍的行高為2行,依次類推。
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
} from 'react-native';
export default class rnText extends Component {
state = {
color: 'blue' //初始藍色
}
render() {
var self = this;
return (
<View style={{flex: 1,justifyContent: 'center',alignItems: 'center',}}>
<Text style={[{color: this.state.color, lineHeight: 25, fontSize: 20,textAlign: 'center', width: 300,}]}
numberOfLines={2}
onLayout={(e)=>{
if (e.nativeEvent.layout.height > 25 ) { //多于一行時改為紅色
this.setState({
color: 'red'
})
}
}}
>
Welcome to React Native! Welcome to React Native! Welcome to React Native!
</Text>
</View>
);
}
}
即主要借用了onlayout的回調。
onLayout function
當掛載或者布局變化以后調用,參數為如下的內容:
{nativeEvent: {layout: {x, y, width, height}}}
嵌套Text的情況
當Text中存在子Text控件時,子Text會繼承父Text的style和其他屬性,但是子Text可以重寫從父輩繼承來的樣式,卻不能重寫其他屬性,如lineHeight, fontSize。
例如:
<Text style={{fontWeight: 'bold', width: 300, color: 'green'}}
numberOfLines={2}
lineHeight={30}
fontSize={15}
>
My name is React Native,
<Text style={{color: 'red'}}
lineHeight={50}
fontSize={25}
>
and I'm always open source.
</Text>
</Text>
顯示結果:
所以,在嵌套的狀態下,我們只需要在父Text上設置好lineHeight, numberOfLines,并做好onLayout回調即可響應多行布局了。