“justifyContent:center”使用“height:100%”(React Native / Flexbox)正确打破布局

问题描述 投票:1回答:1

这是我的简化代码:

<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”将文本居中放在中间时,右边的框完全错误的高度。这是怎么回事?

Normal

With justifyContent

css react-native flexbox
1个回答
0
投票

这是因为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>

让我知道这是否适合你)

© www.soinside.com 2019 - 2024. All rights reserved.