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

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

谢谢


当前回答

<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>

其他回答

使用numberOfLines

<Text numberOfLines={1}>long long long long text<Text>

或者如果你知道/或者可以计算出每行的最大字符数,可以使用JS substring。

<Text>{ ((mytextvar).length > maxlimit) ? 
    (((mytextvar).substring(0,maxlimit-3)) + '...') : 
    mytextvar }
</Text>

在Text组件上使用numberolines参数:

<Text numberOfLines={1}>long long long long text<Text>

会产生:

long long long…

(假设你的容器宽度很短。)


使用ellipsizeMode参数将省略号移动到头部或中间。“Tail”为默认值。

<Text numberOfLines={1} ellipsizeMode='head'>long long long long text<Text>

会产生:

…long long text

注意:Text组件还应该包含style={{flex: 1}},当省略号需要相对于其容器的大小应用时。适用于行布局等。

<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>
<Text ellipsizeMode='tail' numberOfLines={2} style={{width:100}}>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at cursus 
</Text>

结果内框:


<-- width = 100-->
 -----------------
| Lorem ipsum     |
| dolar sit a...  |
 -----------------

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

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