【问题标题】:React Native chat bubble flexbox similar to whatsappReact Native 聊天气泡 flexbox 类似于 whatsapp
【发布时间】:2018-01-08 16:18:05
【问题描述】:

我正在尝试在 React Native 中创建一个类似于 Whatsapp UI 的聊天视图。 我无法理解的是-如何度过时间。这是它在 Whatsapp 中的外观:

请注意,时间本身并不是一个全新的行,而是半行。

同时在最后一条评论中可以看到,如果文字足够长,时间会被推到新的一行。

我已经尝试了几件事:

  1. 使气泡相对,然后在时间元素上使用绝对定位。不幸的是,如果文本足够长,我的时间会与文本重叠。

  2. 使气泡 flexDirection: "row",然后在 1 个视图中显示文本,在另一个视图中显示时间。但是当文本“足够长”时,我不知道如何强制换行。

任何想法如何实现这一目标?

【问题讨论】:

  • 你能分享一些代码吗?

标签: react-native


【解决方案1】:

我设法得到了我想要的东西。它不是 100% 与 whatsapp 相同,但已经足够好了。

我有以下代码:

  <View style={{
      margin: 10, marginTop: 10, marginBottom: 0,
      padding: 10, borderRadius: 5, paddingBottom: 10,
      backgroundColor: cropType ? '#93D14C' : '#F1F0F5'
    }}>
        {this.renderContent(comment)}

      <Text
        style={[styles.muted,
          {
            color: constants.FJMUTEDLIGHT,
            backgroundColor: 'transparent',
            alignSelf: 'flex-end',
            fontSize: 12,
            marginBottom: -5,
            marginTop: 2
          }]}>{moment.utc(comment.created).local().format('HH:mm')}</Text>
    </View>

renderContentHere() 函数可以渲染文本,但它也可以渲染包含文本的复杂视图。最初我想弄清楚文本有多少行并计算行的宽度。 React Native 似乎无法做到这一点,因为 Text 节点上的 onLayout 属性只能告诉您元素的宽度和高度,但不能告诉您 Text 是 2 行还是 3 行。

所以我决定只测量包含评论的 View 并确定它是否有一行或多行。如果它有一条线,我假设我可以将时间设置得比平时高一点。

这就是我最终做的:

<View style={{
          margin: 10, marginTop: 10, marginBottom: 0,
          padding: 10, borderRadius: 5, paddingBottom: 10,
          backgroundColor: cropType ? '#93D14C' : '#F1F0F5'
        }}>

          <View style={this.state.oneLine ? {
            // Since we don't know how long the one line is, just in case add 25px padding on the right
            // this way even if we are dealing with a long line of text it won't end up over the time
            paddingRight: 25
          } : {}}
                onLayout={(e) => {
                  let {height} = e.nativeEvent.layout

                  // if height is less than 30px, then we are dealing with a single line of content
                  if (height < 30) {
                    this.setState({'oneLine': true})
                  }
                }}>

            {this.renderContent(comment)}

          </View>

          <Text
            style={[styles.muted,
              {
                color: constants.FJMUTEDLIGHT,
                backgroundColor: 'transparent',
                alignSelf: 'flex-end',
                fontSize: 12,
                marginBottom: -5,
                // If one line, move the time up - there is enough space
                marginTop: this.state.oneLine ? -10 : 2
              }]}>{moment.utc(comment.created).local().format('HH:mm')}</Text>
        </View> 

如果我们只有一行,文本仍然可能会落后于时间,所以这就是我在 25 像素的文本上应用右填充的原因。这打破了长线,我们最终得到这样的视图:

【讨论】:

    猜你喜欢
    • 2018-11-01
    • 2018-08-10
    • 1970-01-01
    • 2022-11-17
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多