React Native:确定Text组件的行数

React Native:确定Text组件的行数

问题描述:

正如标题所说,我一直试图找到一种方法来确定文本组件在给出文本之后的行数。请看下面的示例。

As the title says, I've been trying to find a way to determine the number of lines the text component AFTER it has been given text. Look at my example below.

<Text>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi semper ut ipsum in ultrices. Vivamus fringilla lacinia odio in accumsan. Proin sit amet pellentesque tortor. Nam mollis sit amet ligula id convallis. Etiam in semper diam. Cras id elit consectetur, interdum ante id, tincidunt nisi. Integer non elit placerat, dignissim nibh at, faucibus sem. Curabitur nec posuere turpis. Vivamus rhoncus nulla vitae mi imperdiet, elementum eleifend mi laoreet. Vestibulum molestie turpis non nibh elementum, sed ornare magna tristique. Aliquam erat volutpat. Phasellus volutpat mi vel tempor finibus.
</Text>

在运行时,如何确定此Text组件呈现的行数。此数字将根据设备而有所不同(例如,iPhone 5将需要渲染更多的线与iPhone 6+,因为它具有较小的屏幕尺寸)。我已经检查了Text组件的源代码,但似乎没有我想要的东西。

At runtime, how can I determine how many lines this Text component has rendered. This number will vary depending on device (eg. iPhone 5 will need to render more lines vs iPhone 6+ as it has a smaller screen size). I've checked the source code for the Text component but there doesn't seem to be anything I'm looking for.

我使用的是React Native 0.24。

I am using React Native 0.24.

任何想法?

干杯。

看起来React Native 0.24实现了onLayout函数

http://facebook.github.io/react-native/docs/text.html#onlayout

It looks like React Native 0.24 implements an onLayout function
http://facebook.github.io/react-native/docs/text.html#onlayout


onLayout函数

使用

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

onLayout function
Invoked on mount and layout changes with
{nativeEvent: {layout: {x, y, width, height}}}

所以看起来你可以传递onLayout回调函数,获取Text组件的高度,然后使用行高进行一些计算行数

So it looks like you could pass an onLayout callback function, get the height of the Text component and then do some calculations using the line height to get to the number of lines