这是我的简化代码:
<View style={{flexDirection: "row", width: 200}}>
<View style={{borderWidth: 2, flex: 1, height: 100}}>
<Text>flex: 1, height: 80</Text>
</View>
<View style={{borderWidth: 2, width: 100, height: "100%", justifyContent: "center"}}>
<Text>width: 100, height: 100%, justifyContent: center</Text>
</View>
</View>
这两个盒子应按高度排列。但是当我添加justifyContent:“center”将文本居中放在中间时,右边的框完全错误的高度。这是怎么回事?
这是因为justifyContent按照给定的空间和高度:'100%'沿着主轴(这里是列)分配所有孩子的子项,这里需要它的父母的高度来分配
有两种方法可以使文本居中:1 - 更改高度:'100%'到定义的高度为100和textAlign:'center'到文本
<View style={{ flexDirection: 'row', width: 200 }}>
<View style={{ borderWidth: 2, flex: 1, height: 100, }}>
<Text>flex: 1, height: 80</Text>
</View>
<View
style={{
borderWidth: 2,
width: 100,
height: 100,
justifyContent : 'center'
}}
>
<Text style={{textAlign : 'center'}} >width: 100, height: 100, justifyContent: center</Text>
</View>
</View>
要么
2 - 为父级和textAlign指定一个定义的高度:'center'到文本
<View style={{ flexDirection: 'row', width: 200, height : 100 }}>
<View style={{ borderWidth: 2, flex: 1, height: 100, }}>
<Text>flex: 1, height: 80</Text>
</View>
<View
style={{
borderWidth: 2,
width: 100,
height: '100%',
justifyContent : 'center'
}}
>
<Text style={{textAlign : 'center'}} >width: 100, height: 100%, justifyContent: center</Text>
</View>
</View>
让我知道这是否适合你)