React Native:确定文本组件的行数 [英] React Native: Determine number of lines of Text component

查看:50
本文介绍了React Native:确定文本组件的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我一直试图找到一种方法来确定文本组件在被赋予文本后的行数.看看我下面的例子.

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.

有什么想法吗?

干杯.

推荐答案

我想提供一个现代的解决方案.现在有一个 onTextLayout 事件,它包含一个 lines 数组,可以确定正在渲染的行数.lines 数组中还有其他详细信息,例如每行的实际高度和宽度,可进一步用于确定文本是否被截断.

I want to provide a modern solution. There is now a onTextLayout event that includes an array of lines which can be determined what number of lines are being rendered. There's other details in the lines array like actual height and width of every line which can be further used to determine if the text is being truncated.

const NUM_OF_LINES = 5;
const SOME_LONG_TEXT_BLOCK = 'Lorem ipsum ...';

function SomeComponent () { 
  const [ showMore, setShowMore ] = useState(false);
  const onTextLayout = useCallback(e => {
    setShowMore(e.nativeEvent.lines.length > NUM_OF_LINES);
  }, []);

  return (
    <Text numberOfLines={NUM_OF_LINES} onTextLayout={onTextLayout}>
      {SOME_LONG_TEXT_BLOCK}
    </Text>
  );
}

这篇关于React Native:确定文本组件的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆