React Native - 两个项目:一个在左边,一个在中间

React Native - two items: one on the left, one in the center

我一直在努力在以下位置对齐两个项目:第一个应该在行的左侧,第二个元素需要在行的中心。

下面的代码没有完全居中我的第二个元素:

<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>

            <View style={{ paddingLeft: 10 }}>
                <Text style={{ fontSize: 20, color: 'red', fontWeight: '200' }}>LEFT_ELEM</Text>
            </View>
            <View style={{paddingRight: 10 }}>
            <Text>
                CENTER
            </Text>
            </View>
            {/* Empty view so that space-between works? */}
            <View
                style={{paddingRight: 10 }}>
            </View>
 </View>

这是我最接近我想要的结果。但是,它并不能解决问题。谁能知道成功实施此计划的最佳方法?

您需要将 flex: 1 添加到 parent 视图和 children 视图(所有 children 将具有 flex: 1,如果您希望它们全部大小相等,否则为每个 child 单独查看定义 width/flex。

试试这个:

      <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
        <View style={{ flex: 1, paddingLeft: 10 }}>
          <Text style={{ fontSize: 20, color: 'red', fontWeight: '200' }}>LEFT_ELEM</Text>
        </View>
        <View style={{ flex: 1, paddingRight: 10 }}>
          <Text style={{ textAlign:'center' }}>CENTER</Text>
        </View>
        <View
          style={{ flex: 1, paddingRight: 10 }}>
        </View>
      </View>

已将 style={{ textAlign:'center' }} 添加到居中视图 child 中的文本,让您了解其居中位置。你可以 modify/remove 它。

  <View style={{flex:1, flexDirection: 'row', justifyContent: 'space-around'}}>
        <View style={{width: 50, height: 50}}>
            <Text style={{ fontSize: 20, color: 'red', fontWeight: '200' }}>LEFT_ELEM</Text>
        </View>
        <View style={{ width: 50, height: 50}}>
            <Text>CENTER</Text>
        </View>
        <View style={{ width: 50, height: 50}}/>
 </View>

当我学习Android时,有人告诉我不要使用太多'layers'的组件。在这种理念下,​​我决定对左侧元素使用 'absolute' 属性 以获得更简单的结果。在这个方案中,'left'项几乎贴在左边的墙上。

<View
    style={{
        height: 50,
        flexDirection: 'row', // a must
        alignItems: 'center', // to make items center vertically.
        justifyContent: 'center' // to make the second item center horizontally.
    }}
>
    <MaterialIcons
        style={[styles.titleIcon, { position: 'absolute', left: 0 }]} // on left, still center vertically.
        name='arrow-back'
        onPress={() => {
            navigation.goBack();
        }}
    />
    <Text style={styles.titleText}>{result.name}</Text> // on center automatically
</View>