我设法得到了我想要的东西。它不是 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 像素的文本上应用右填充的原因。这打破了长线,我们最终得到这样的视图: