Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

react native - How to justify (left, right, center) each child independently?

In react native I have:

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

with these styles:

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

This is the effect I get:

undesired

This is the effect I want:

desired

In the first example, the spacing between items is equal.

In the second example, each item is justified differently. The first item is left-justified. The second item is center-justified. The third, right-justified.

This question is similar, but it looks like react native does not support margin: 'auto'. Furthermore, the other answers only work if you only care about left and right justification, but no one really addresses center justification without auto margin.

I am trying to make a navigation bar in react native. The vanilla ios version looks like this:

ios
(source: apple.com)

How do I do something similar? I'm mainly concerned with centering.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way is to use nested View (flex containers) for 3 different regions and set flex:1 to left and right region

<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',
  }
});

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...