You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native SVG中Rect设置height:100%无法填满屏幕如何解决?

解决Rect无法填满屏幕高度的问题

问题原因

你代码里的viewBox="0 0 100 100"会强制Svg保持1:1的宽高比,而屏幕通常是长条形,所以Svg会按比例缩放,导致高度无法填满整个屏幕。

解决方案

方案1:移除viewBox属性

直接去掉viewBox,让Svg自适应容器尺寸,Rect的100%宽高就能填满整个屏幕:

<View style={StyleSheet.absoluteFill}>
  <Svg height="100%" width="100%">
    <Rect width="100%" height="100%" fill="red" />
  </Svg>
</View>

方案2:保留viewBox并添加preserveAspectRatio属性

如果需要保留viewBox,添加preserveAspectRatio="none"取消宽高比限制,让Svg拉伸适配容器:

<View style={StyleSheet.absoluteFill}>
  <Svg height="100%" width="100%" viewBox="0 0 100 100" preserveAspectRatio="none">
    <Rect width="100%" height="100%" fill="red" />
  </Svg>
</View>

方案3:用flex布局替代百分比设置

给Svg设置flex:1,让它自动填满父容器的剩余空间,配合preserveAspectRatio="none"使用:

<View style={StyleSheet.absoluteFill}>
  <Svg style={{ flex: 1 }} viewBox="0 0 100 100" preserveAspectRatio="none">
    <Rect width="100%" height="100%" fill="red" />
  </Svg>
</View>

内容的提问来源于stack exchange,提问作者user16967562

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:24:56