React-Native带flexWrap容器内用space-between导致子元素溢出问题咨询
问题原因
这个表现是React Native依赖的Yoga布局引擎的已知实现缺陷,仅出现在原生端,web端使用标准W3C flex布局逻辑所以表现正常:
当横向父容器设置flexWrap: 'wrap'时,Yoga在计算未显式指定高度的纵向排列子容器的高度时,会错误忽略justifyContent: 'space-between'的布局规则,直接以子元素的总高度作为子容器高度。而父容器的整体高度会被子元素中更高的那一项(本例中第二个子容器总高度300)撑开,第一个子容器高度仅为200,此时justifyContent: 'space-between'需要将剩余空间分散为上下边距,就会导致子元素溢出容器。
解决方案
有三种可行的兼容方案,都可以保留flexWrap属性同时实现预期布局:
方案1:给父容器添加alignItems: 'stretch'
该属性会强制所有纵向子容器自动撑满父容器的高度,让Yoga获得明确的高度计算基准,规避自动计算错误,代码修改量最小:
<View style={{ backgroundColor: 'purple', flexDirection: 'row', flexWrap: 'wrap', alignItems: 'stretch' }}> <View style={{ borderWidth: 1, borderColor: 'white', justifyContent: 'space-between' }}> <View style={{ backgroundColor: 'red', height: 100, width: 100 }} /> <View style={{ backgroundColor: 'green', height: 100, width: 100 }} /> </View> <View style={{ borderWidth: 1, borderColor: 'white', justifyContent: 'space-between' }}> <View style={{ backgroundColor: 'blue', height: 150, width: 100 }} /> <View style={{ backgroundColor: 'yellow', height: 150, width: 100 }} /> </View> </View>
方案2:用marginTop: 'auto'替代justifyContent: 'space-between'
去掉纵向子容器的justifyContent: 'space-between'属性,给需要靠下对齐的子元素添加marginTop: 'auto',同样可以实现上下分散对齐的效果,不会触发Yoga的计算缺陷:
<View style={{ backgroundColor: 'purple', flexDirection: 'row', flexWrap: 'wrap' }}> <View style={{ borderWidth: 1, borderColor: 'white' }}> <View style={{ backgroundColor: 'red', height: 100, width: 100 }} /> <View style={{ backgroundColor: 'green', height: 100, width: 100, marginTop: 'auto' }} /> </View> <View style={{ borderWidth: 1, borderColor: 'white' }}> <View style={{ backgroundColor: 'blue', height: 150, width: 100 }} /> <View style={{ backgroundColor: 'yellow', height: 150, width: 100 }} /> </View> </View>
方案3:显式指定子容器高度
如果布局高度可提前预估,直接给所有纵向子容器设置统一的固定高度,也可以解决该问题。如果高度需要动态适配,可以通过onLayout回调获取最高子容器的高度,再统一赋值给所有子容器即可。
内容的提问来源于stack exchange,提问作者guiccbr
相关产品推荐
相关产品推荐

