如何独立地对每个子元素进行左对齐、右对齐或居中对齐?

60

在 React Native 中我有:

<View style={styles.navBar}>
  <Text>{'<'}</Text>
    <Text style={styles.navBarTitle}>
      Fitness & Nutrition Tracking
    </Text>
  <Image source={icon} style={styles.icon}/>
</View>

使用这些样式:

{
    navBar: {
        height: 60,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    navBarTitle: {
        textAlign: 'center',
    },
    icon: {
        height: 60,
        resizeMode: 'contain',
    },
}

这是我得到的效果:

undesired

这是我想要的效果:

desired

在第一个示例中,项目之间的间距相等。

在第二个示例中,每个项目的对齐方式不同。第一个项目左对齐。第二个项目居中对齐。第三个项目右对齐。

这个问题类似,但看起来react native不支持margin: 'auto'。此外,其他答案仅适用于左右对齐,但没有人真正解决了没有自动边距的居中对齐。

我正在尝试在react native中制作导航栏。vanilla ios版本如下:

ios
(来源:apple.com)

如何做类似的事情?我主要关心居中对齐。

4个回答

111

一种方法是使用嵌套的视图(flex容器)来划分三个不同区域,并将左右区域设置为flex:1

<View style={styles.navBar}>
  <View style={styles.leftContainer}>
    <Text style={[styles.text, {textAlign: 'left'}]}>
      {'<'}
    </Text>
  </View>
  <Text style={styles.text}>
    Fitness & Nutrition Tracking
  </Text>
  <View style={styles.rightContainer}>
    <View style={styles.rightIcon}/>
  </View>
</View>

const styles = StyleSheet.create({
  navBar: {
    height: 60,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: 'blue',
  },
  leftContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-start',
    backgroundColor: 'green'
  },
  rightContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
    backgroundColor: 'red',
  },
  rightIcon: {
    height: 10,
    width: 10,
    resizeMode: 'contain',
    backgroundColor: 'white',
  }
});

在此输入图片描述


谢谢。我仍在学习 flex 属性的行为。我实现了您的解决方案,但因为我忘记了 flexDirection 的默认值是 column,所以我编辑了您的回答。 - Croolsby
谢谢。是的,你说得对。现在更容易理解了。已批准。 - agenthunt
6
但是 styles.text 在哪里?我找不到它。 - Sultan Ali
你可以将它从样式对象中删除或添加。 - agenthunt
我一直在痛苦地调试,后来我意识到我没有加上 flex: 1,加上之后就可以了。我想知道为什么 flex: 1 如此神奇? - Zennichimaro
中间组件的 styles.text 在哪里? - Srithar Rajendran

9

2

1
使用这个。
marginLeft: "auto",
marginRight: "auto"

在哪里?它是做什么的? - Hans Bouwmeester
就像问题已经提到的那样,在React Native中,margin auto不起作用。 - Guy Incognito
1
这在2021年的React Native中对我有效。 - JCraine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接