【问题标题】:React Native handling ellipsis when multiple Text components in a row当连续多个文本组件时,React Native 处理省略号
【发布时间】:2016-07-13 09:46:27
【问题描述】:

我正在尝试在 React Native 中构建一个 cmets 部分,但我无法正确处理文本溢出和省略号。

结构简单,如下所示:

理想情况下,当用户名足够长时,它应该被修剪,并且动作名称应该一直推到右边,直到它达到这样的时间戳:

我得到的最接近的是使用此代码:

const styles = StyleSheet.create({
    commentRow: {
        padding: 10
    },
    commentTopRow: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    commentTitle: {
        flex: 1
    },
    author: {
        fontWeight: '500'
    },
    commentBody: {
        paddingTop: 5,
        paddingBottom: 5
    }
});

<View style={styles.commentRow}>
    <View style={styles.commentTopRow}>
        <Text style={styles.commentTitle} numberOfLines={1}>
            <Text style={styles.author}>User Name</Text>
            <Text style={styles.action}> commented</Text>
        </Text>
        <Text style={styles.timestamp}>8h</Text>
    </View>
    <Text style={styles.commentBody}>comment body</Text>
</View>

产生以下结果:

任何帮助找出可以处理这两种情况的独特结构和样式集将不胜感激。

谢谢!

【问题讨论】:

  • 作为旁注,我还有一个中间版本,其中长用户名可以使用,但短用户名被破坏,始终将“评论”固定在右侧。这没有 commentTitle 包装器,flex: 1numberOfLines={1} 设置在 author 上。

标签: layout react-native flexbox ellipsis


【解决方案1】:

根据 Facebook 的guide

在 React Native 中,flex 的工作方式与在 CSS 中不同。 flex 是一个数字而不是一个字符串,它根据https://github.com/facebook/css-layout 的 css-layout 库工作。

当 flex 为 -1 时,组件通常根据宽度和高度调整大小。但是,如果没有足够的空间,组件会缩小到它的 minWidth 和 minHeight。

所以基本上你需要为你的组件设置正确的flex 值。我想您不希望 commented8h 缩小。然后,您需要将这些组件的flex 值设置为0,以使它们不灵活地收缩。并将0设置为long long user name,使其在空间不足时灵活收缩。

【讨论】:

  • 您能否将long user name 值更正为-1 而不是0
【解决方案2】:

这会成功的

 <View style={styles.commentRow}>
     <View style={styles.commentTopRow}>
         <View style={styles.commentTitle}>
             <Text numberOfLines={1}>
                 <Text style={styles.author}>User Name</Text>
                 <Text style={styles.action}> commented</Text>
             </Text>
         </View>
         <View>
            <Text style={styles.timestamp}>8h</Text>
         </View>
     </View>
     <Text style={styles.commentBody}>comment body</Text>
 </View>

总之,你应该使用View来布局,而不是Text

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-10
    • 2020-03-18
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    相关资源
    最近更新 更多