Text控件是React Native最常用的幾個(gè)控件之一了纵揍,因?yàn)閹缀鯖](méi)有哪個(gè)應(yīng)用不使用文案展示功能的蛔屹。在展示文案時(shí)灌具,我們常常需要限定Text顯示區(qū)域的寬度,而文本出現(xiàn)超長(zhǎng)時(shí)何什,要么選擇截?cái)嘧榱ǎ催x擇換行。當(dāng)選擇換行時(shí)处渣,我們要對(duì)換行做出一些響應(yīng)伶贰,比如我們需要因此調(diào)整所在容器的高度等。本文就演示一下如何動(dòng)態(tài)檢測(cè)Text控件出現(xiàn)了換行罐栈。
單個(gè)Text黍衙,無(wú)嵌套的情況
參照以下步驟:
- 設(shè)置numberOfLines屬性,指定最大行數(shù)
- 設(shè)置lineHeight樣式悠瞬,指定行高
- 設(shè)置onLayout屬性们豌,并在回調(diào)函數(shù)中判斷當(dāng)前控件的總高度: 1倍的lineHeight為1行,2倍的行高為2行浅妆,依次類(lèi)推望迎。
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
} from 'react-native';
export default class rnText extends Component {
state = {
color: 'blue' //初始藍(lán)色
}
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 ) { //多于一行時(shí)改為紅色
this.setState({
color: 'red'
})
}
}}
>
Welcome to React Native! Welcome to React Native! Welcome to React Native!
</Text>
</View>
);
}
}
即主要借用了onlayout的回調(diào)。
onLayout function
當(dāng)掛載或者布局變化以后調(diào)用凌外,參數(shù)為如下的內(nèi)容:
{nativeEvent: {layout: {x, y, width, height}}}
嵌套Text的情況
當(dāng)Text中存在子Text控件時(shí)辩尊,子Text會(huì)繼承父Text的style和其他屬性,但是子Text可以重寫(xiě)從父輩繼承來(lái)的樣式康辑,卻不能重寫(xiě)其他屬性摄欲,如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>
顯示結(jié)果:
所以疮薇,在嵌套的狀態(tài)下胸墙,我們只需要在父Text上設(shè)置好lineHeight, numberOfLines,并做好onLayout回調(diào)即可響應(yīng)多行布局了按咒。