【问题标题】:How to get a Truncated text value in React Native?如何在 React Native 中获取截断的文本值?
【发布时间】:2021-01-23 09:32:40
【问题描述】:

当我们使用 numberOfLines 时,是否有某种方法可以在 RN 中获取截断文本?

例如:

组件

 <Text style={{width: 50}} numberOfLines={3}>
    Some very long text with tons of useful info
 </Text>

输出

 Some
 very
 long...

我想知道最终用户可以看到的文本到底是什么。有没有可能?

感谢您的帮助!

附:我尝试使用 Ref 功能来获取内容,但它包含带有整个文本的道具,所以它没有帮助

【问题讨论】:

    标签: react-native text ellipsis truncated


    【解决方案1】:

    你可以像这样使用 onTextLayout 属性。

    e.nativeEvent.lines 有文本中的每一行,如果你有文本和行数,那么你可以像下面这样使用这个数组并查看每一行中的文本。这适用于 Android 不确定网络。

    export default function App() {
      
      const text =
        "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
    
      const lines = 3;
    
      return (
        <View style={{ flex: 1 }}>
          <Text
            onTextLayout={(e) => {
              const shownText = e.nativeEvent.lines.slice(0, lines).map((line) => line.text).join('');
              alert(shownText);
              const hidenText = text.substring(shownText.length);
              alert(hidenText);
            }}
            numberOfLines={lines}
            onPress={this.toggleUser}>
            {text}
          </Text>
        </View>
      );
    }
    

    【讨论】:

    • 谢谢。你是对的,它适用于移动设备。有没有其他方法可以达到同样的效果?
    • 这就像我所知道的最好的方式,因为它提供线路级别的访问,我们无法以任何其他方式计算线路
    【解决方案2】:
    You can combine numberOfLines and width / flex prop to achieve this effect.
    
    <Text numberOfLines={1} style={{ width: 100 }}>
        Lorem Ipsum is simply dummy text of the printing and
        typesetting industry. Lorem Ipsum has been the industry's
        standard dummy text ever since the 1500s, when an unknown
        printer took a galley of type and scrambled it to mak
    </Text>
    

    【讨论】:

    • 感谢您的回答,但很抱歉,我不明白您的回答。我想将截断的文本作为变量接收,以便稍后对其进行一些操作。在这种情况下 flex/width 属性如何帮助我们?
    猜你喜欢
    • 2020-09-30
    • 2023-01-19
    • 1970-01-01
    • 2019-11-27
    • 2021-04-14
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多