我在我的应用程序中有一个很长的文本,我需要截断它,并在结尾添加三个点。

我怎么能在React本机文本元素中做到这一点?

谢谢


当前回答

使用text属性numberolines ={1}来实现文本的省略号,它会自动截断带有省略号的文本,你可以指定ellipsizeMode为"head", "middle", "tail"或"clip" 默认为tail

https://reactnative.dev/docs/text#ellipsizemode

其他回答

如果你想读取更多的行为,那么你可以使用react-native-read-more-text库:

NPM I react-native-read-more-text -save

<ReadMore
  numberOfLines={1}
  renderTruncatedFooter={(handlePress) => { return <Text onPress={handlePress} style={{ color: 'grey' }}>show more</Text> }}
  renderRevealedFooter={(handlePress) => { return <Text onPress={handlePress} style={{ color: 'grey' }}>show less</Text> }}
>
  <Text>yourText</Text>
</ReadMore>

文档:https://github.com/expo/react-native-read-more-text

当内容小于numberolines时,要隐藏“read more”,你可以使用三元操作符:

{
  'yourText'.length > 50
  ?
  <ReadMore
    numberOfLines={1}
    renderTruncatedFooter={(handlePress) => { return <Text onPress={handlePress} style={{ color: 'grey' }}>show more</Text> }}
    renderRevealedFooter={(handlePress) => { return <Text onPress={handlePress} style={{ color: 'grey' }}>show less</Text> }}
  >
    <Text>yourText</Text>
  </ReadMore>
  :
  <Text>yourText</Text>
}

使用text属性numberolines ={1}来实现文本的省略号,它会自动截断带有省略号的文本,你可以指定ellipsizeMode为"head", "middle", "tail"或"clip" 默认为tail

https://reactnative.dev/docs/text#ellipsizemode

您可以使用ellipsizeMode和numberolines。 如

<Text ellipsizeMode='tail' numberOfLines={2}>
  This very long text should be truncated with dots in the beginning.
</Text>

https://facebook.github.io/react-native/docs/text.html

<View 
   style={{
        flexDirection: 'row',
        padding: 10,
    }}
>
  <Text numberOfLines={5} style={{flex:1}}>
       This is a very long text that will overflow on a small device This is a very 
       long text that will overflow on a small deviceThis is a very long text that 
       will overflow on a small deviceThis is a very long text that will overflow 
       on a small device
  </Text>
</View>

Const styles = theme => ({ contentClass: { 溢出:“隐藏”, textOverflow:“省略”, 显示:“-webkit-box”, WebkitLineClamp: 1、 WebkitBoxOrient:“垂直” } }) Render () { 回报( < div className = {classes.contentClass} > {“内容”} < / div > ) }