Как получить усеченное текстовое значение в React Native?

#react-native #text #ellipsis #truncated

#react-native #текст #многоточие #усеченный

Вопрос:

Существует ли какой-либо способ получить усеченный текст в RN, когда мы используем numberOfLines?

Например:

Компонент

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

Вывод

  Some
 very
 long...
  

Я хочу знать, какой именно текст виден конечному пользователю. Возможно ли это как-то?

Спасибо за любую помощь!

PS Я пытался использовать функции Ref для получения содержимого, но он содержит реквизиты со всем текстом, поэтому это не помогло

Ответ №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>
  );
}
  

Комментарии:

1. Спасибо. Вы правы, это работает на мобильных устройствах. Существует ли какой-либо другой способ добиться того же результата?

2. это похоже на лучший способ из того, что я знаю, поскольку он предоставляет доступ на уровне строки, и мы не можем вычислять строки каким-либо другим способом

Ответ №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>
  

Комментарии:

1. Спасибо за ответ, но извините, я не понимаю вашего ответа. Я хотел бы получить усеченный текст в качестве переменной, чтобы позже выполнить с ним некоторые операции. Как поддержка flex / width может помочь нам в этом случае?