简体   繁体   中英

React-Native: Center two text components in a single View component

I'm trying to center two separate texts in their components, I'm using ‍‍ react-native and native-base . I cannot center the text vertically and horizontally within the Text component itself. I have divided into colors to see the problem graphically.

The elements:

<View
  style={{
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'red'
  }}>
  <Text uppercase={false} style={styles.buttonTextLeft}>
    {title}
  </Text>
  <Text uppercase={false} style={styles.buttonTextLeftGreen}>
    {subTitle}
  </Text>
</View>

The styles:

buttonTextLeft: {
  fontFamily: 'Cuprum-Bold',
  fontSize: normalize(20),
  color: '#005f99',
  flex: 1,
  flexDirection: 'row',
  backgroundColor: 'yellow'
},
buttonTextLeftGreen: {
  fontFamily: 'Cuprum-Bold',
  fontSize: normalize(20),
  color: '#94cf1c',
  flex: 1,
  flexDirection: 'row',
  backgroundColor: 'green'
},

what you see commented are all the tests I did. certainly, it is stupid but I have not yet solved, do you have any idea? Thanks.

SOLUTION

For those who had the same problem, I enter the code of my correct and clean current situation (without the backgroundColor):

JS

<View
  style={{
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
  }}
>
  <Text uppercase={false} style={styles.buttonTextLeft}>
    {title}
  </Text>
  <Text uppercase={false} style={styles.buttonTextLeftGreen}>
    {subTitle}
  </Text>
 </View>

Styles

buttonTextLeft: {
  fontFamily: 'Cuprum-Bold',
  fontSize: normalize(20),
  flex: 1,
  flexDirection: 'row',
  lineHeight: normalize(20),
  paddingVertical: normalize(4),
  color: '#005f99',
},
buttonTextLeftGreen: {
  fontFamily: 'Cuprum-Bold',
  fontSize: normalize(20),
  flex: 1,
  flexDirection: 'row',
  lineHeight: normalize(20),
  paddingVertical: normalize(4),
  color: '#94cf1c',
},

Maybe I didn't understand your problem truly, I guess your problem is inside green and yellow area.

I had same issue and for handling this issue I used line-height: 20 and paddingVertical: 5 . the 20 and 5 numbers are sample and for my project design. you put your numbers instead of them.

Setting the line height of the text to be the desired height of the box should work. For example if you want the yellow box to be 50 tall you would set lineHeight: 50 on the text.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM