1. 程式人生 > >React Native 之 Text居中顯示

React Native 之 Text居中顯示

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Image,
  Text,
  TouchableHighlight,
  View
} from 'react-native';

import ImageEqualEnlarge from './ImageEqualEnlarge.js' 

export default class ViewProject extends Component {

  render() {
    return (
      <View style={styles.container}>
         <Text style={styles.textStyle}>
            happy
        </Text>
        <Text style={styles.textStyle}>
            憂傷 
        </Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex:1,
    justifyContent: 'center',
    alignItems:'center',
  },
  textStyle:{
   height:100,
   width:200,
   fontSize:30,
   backgroundColor:'gray',
   textAlign:'center',   
   justifyContent: 'center', //雖然樣式中設定了 justifyContent: 'center',但無效

   margin:5

 }});AppRegistry.registerComponent('ViewProject', () => ViewProject);

Text 元件的樣式鍵 textAlign 和 justifyContent 都設定為center,這樣字串應該垂直和水平都居中,但事實上,只會水平居中顯示效果如圖

正確的做法是 Text元件外邊包一層View,且Text元件的樣式除了fontSize鍵值其它樣式鍵值都移到外層View的樣式中 如下程式碼實現:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Image,
  Text,
  TouchableHighlight,
  View
} from 'react-native';

import ImageEqualEnlarge from './ImageEqualEnlarge.js' 

export default class ViewProject extends Component {

  render() {
    return (
      <View style={styles.container}>
         <View style={styles.ViewForTextStyle}>
         <Text style={styles.newTextStyle}>
            happy
        </Text>
        </View>
        <View style={styles.ViewForTextStyle}>
        <Text style={styles.newTextStyle}>
            憂傷 
        </Text>
        </View>
      </View>
    );
  }


}



const styles = StyleSheet.create({
  container: {
    flex:1,
    justifyContent: 'center',
    alignItems:'center',
  },
  newTextStyle:{
   fontSize:30,
  },
  textStyle:{
   height:100,
   width:200,
   fontSize:30,
   backgroundColor:'gray',
   textAlign:'center',
   justifyContent: 'center',
   margin:5
  },
  ViewForTextStyle:{
    height:100,
    width:200,
    alignItems:'center',
    justifyContent: 'center',
    backgroundColor:'gray',
    margin:5
  }

});
AppRegistry.registerComponent('ViewProject', () => ViewProject);