如何在react-native中的多行文本中断后确定“更多”链接/按钮的位置

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在react-native中的多行文本中断后确定“更多”链接/按钮的位置相关的知识,希望对你有一定的参考价值。

我想在一个本机应用程序中实现Instagram的字幕分解功能(长文本中断后的“更多”链接),但可以选择确定换行符的确切字符位置以放置“更多”链接。

例如,如果我在标题中有以下文字:

Lorem存有悲坐阿梅德,人们认为女佣,一个妖娆的他们,你,他,只是,攻击。开发商在同样西柳斯做足球,大海。凡便利电视喜欢足球,首先双方lucilius。当朝天iriure,两场比赛礼貌理解。随着不适的一部分,治好了他们,并且,在我WISI的正直作为的其余部分。

并且给定numberOfLines={2},它在“更多”(不是确切的2行)之前显示(比方说)一行半的文本。

Desired view of my example at this stage

答案

实际上有一个用于此目的的库: react-native-read-more-text

这是Github的discussion。基本上这个想法是使用computeLines函数来虚拟地计算每条线的长度。

另一答案

我不知道它到底会帮到你。但这就是我在我的案例中所做的。它对我有用

import * as React from 'react';
import {
  Text,
  View,
  StyleSheet,
  TextInput,
  TouchableOpacity,
} from 'react-native';

export default class Myapp extends React.Component<{}> {
  constructor(props) {
    super(props);
    this.state = {
      text: '...more' + '
',
      number: 2,
    };
    this.dl =
      'Lorem ipsum dolor sit amet, putant ancillae voluptaria eos te, eum et justo impetus. Tincidunt efficiendi eu mei, sea at aeque persius. Quo commodo molestie similique eu, pri ei utroque lucilius. Eum cu everti iriure, in duo ludus urbanitas intellegam. Partiendo molestiae et eos, mei wisi cetero recteque ex.sddaefrwtttb tguirdg';
  }

  render() {
    return (
      <View style={styles.container}>
        <Text numberOfLines={this.state.number} ellipsizeMode={'middle'}>
          {this.dl.substr(0, 80)}
          <Text
            onPress={() =>
              this.setState({ number: null, text: this.dl.substr(80) })
            }>
            {this.state.text}
          </Text>
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

它并不完美,但我认为它会给你一个想法Expo Link

以上是关于如何在react-native中的多行文本中断后确定“更多”链接/按钮的位置的主要内容,如果未能解决你的问题,请参考以下文章

当有多行时,“手动”处理 UITextView 的文本和光标位置中断

ScrollView 中的多行文本被截断

删除行时如何使多行TextInput缩小(React-Native)?

iOS drawInRect:属性使用多行执行文本截断

集合视图单元格中的多行标签在重用后中断

使用 React-Native 制作多行扩展 TextInput