【问题标题】:How to shrink or force equal height between components in row如何缩小或强制行中组件之间的高度相等
【发布时间】:2020-05-26 08:21:40
【问题描述】:

我是 RN 新手,我无法处理高度优先涉及的图像,我似乎无法找到解决方法。

基本上,我希望图像的高度始终等于该行中下一个视图的总高度(styles.itemDetails 的视图)。

图像总是增长到它的图像原生高度,如果我使用aspectRatio,它会忽略resizeMode 属性并且不会增长到可用空间。

组件:

    <View style={styles.item}>
      <Image style={styles.itemImg} source={source} />
      <View style={styles.itemDetails}>
        <Text>{poi.name}</Text>
        <Text>{poi.conciseDescription}</Text>
      </View>
    </View>

样式:

const styles = StyleSheet.create({
  item: {
    marginTop: 8,
    marginHorizontal: 8,
    borderRadius: 8,
    backgroundColor: '#E5E5E5',
    flexDirection: 'row',
  },
  itemImg: {
    flex: 1,
    borderTopLeftRadius: 8,
    borderBottomLeftRadius: 8,
    resizeMode: 'cover',
  },
  itemDetails: {
    flex: 2,
    margin: 16,
    backgroundColor: 'green',
  },
  itemTitle: {
    fontSize: 22,
  },
});

【问题讨论】:

  • 你必须在容器item:{display:flex}上设置显示为flex
  • @alan_jouhar 谢谢,但添加 display:flex 似乎根本没有效果。

标签: javascript css reactjs react-native flexbox


【解决方案1】:

您可以通过 onLayout 事件获取 itemDetails 的高度并设置为图像高度

const [imageHeight, setImageHeight] = useState(0)

<View style={styles.item}>
  <Image style={[styles.itemImg, {height: imageHeight}]} source={source} />
  <View 
       style={styles.itemDetails} 
       onLayout={e => { setImageHeight(e.nativeEvent.layout.height) }}
  >
    <Text>{poi.name}</Text>
    <Text>{poi.conciseDescription}</Text>
  </View>
</View>

【讨论】:

  • 谢谢,这个好像差不多了,但是由于某种原因,它仍然在图像下方留下了一些空白,不知道为什么,我会继续检查它
  • 我发现高度没有margin 值,将它与onLayout 的高度结合起来效果很好。不确定是否有另一种方法可以做到这一点而不必使用回调,但现在可以这样做。谢谢。
【解决方案2】:

尝试将 itemImg 设置为 1em:

img {height: 1em;}
<div>
  <img src="http://www.w3.org/html/logo/downloads/HTML5_Logo_128.png" /> Your Text
</div>

如果这不起作用,您可以尝试将父元素“item”设置为inline-flex 和/或删除flex: 1,

【讨论】:

  • 遗憾的是,React Native 中似乎没有em 单元,删除flex:1 会导致图像占据容器的整个宽度(我认为是flex:0
猜你喜欢
  • 2010-10-14
  • 2016-10-12
  • 2018-12-14
  • 2014-01-13
  • 2012-05-01
  • 1970-01-01
  • 2014-11-07
  • 2011-02-16
相关资源
最近更新 更多