Flex 盒子动态宽度和高度

2024-01-13

我正在尝试使用反应本机创建消息视图,例如:

如你看到的:

  1. 气泡具有基于内容的动态宽度和高度
  2. 气泡有一个最大宽度,并且它们向下生长

我正在尝试使用 React Native 来重新创建这个,但是我只能实现(2)并且不确定如何实现这两个目标..这是我迄今为止所拥有的:

  <View style={{flex:1,backgroundColor:'blue',flexDirection:'row'}}>
     <View style={{backgroundColor:'orange'}}>
            <View style={{width:90,flex:1}}>
              <Text>123</Text>
              </View>
     </View>
     <View style={{flex:0.25,backgroundColor:'red'}}>
              <Text>123</Text>
     </View>
  </View>

如果我增加橙色视图来代表一个大气泡,那么它就会离开屏幕......例如:


我有同样的问题。我尝试了很多事情,包括将包装纸到处放(就像前面的答案中提到的那样)。他们都没有工作。

@André Junges 的答案不正确,因为 @kingkong 和我有不同的要求。

然后,我看到flex也可以取值-1。并且设置它解决了问题。

这是代码:

const messages = [
              'hello',
              'this is supposed to be a bit of a long line.',
              'bye'
              ];
return (
  <View style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: 150,
            alignItems: 'flex-end',
            justifyContent: 'flex-start',
            backgroundColor: '#fff',
            }}>

{messages.map( (message, index) => (
  <View key={index} style={{
                  flexDirection: 'row',
                  marginTop: 10
                }}>
    <View style={{
                  flex: -1,
                  marginLeft: 5,
                  marginRight: 5,
                  backgroundColor: '#CCC',
                  borderRadius: 10,
                  padding: 5,
                }}>
      <Text style={{
                    fontSize: 12,
                    }}>
        {message}
      </Text>
    </View>
    <Image source={require('some_path')} style={{width:30,height:30}} />
   </View> 
  ))} 
 </View>
)

这是结果:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flex 盒子动态宽度和高度 的相关文章

随机推荐