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 (

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!

);

}

}

即主要借用了onlayout的回调。

onLayout function

当挂载或者布局变化以后调用,参数为如下的内容:

{nativeEvent: {layout: {x, y, width, height}}}

嵌套Text的情况

当Text中存在子Text控件时,子Text会继承父Text的style和其他属性,但是子Text可以重写从父辈继承来的样式,却不能重写其他属性,如lineHeight, fontSize。

例如:

numberOfLines={2}

lineHeight={30}

fontSize={15}

>

My name is React Native,

lineHeight={50}

fontSize={25}

>

and I'm always open source.

显示结果:

8a5dd9af3021

所以,在嵌套的状态下,我们只需要在父Text上设置好lineHeight, numberOfLines,并做好onLayout回调即可响应多行布局了。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐