felix-cao / Blog

A little progress a day makes you a big success!
31 stars 4 forks source link

React Native 入门 --- Text 组件和 Image 组件 #115

Open felix-cao opened 5 years ago

felix-cao commented 5 years ago

一、Text 组件

Text 组件是一个用于显示文本的 React 组件, 对应 iOS 上的 UILabelAndroid 上的 TextView 组件,

1.1 不可以用其他组件来显示文本

<View style={{flex: 1, justifyContent: 'center', paddingTop: 100, alignItems: 'center'}}>
    <Text>Felix Cao</Text>
    <View>Felix Cao</View>  
</View>

报错提示: Invariant Violation: Text strings must be rendered within a <Text> component. 删除 View 部分就可以了

1.2 文字居中

Text 有一个布局属性 textAlign enum(‘auto’, ‘left’, ‘right’, ‘center’, ‘justify’) 可以用来控制 Text 中文字 水平 对齐,只能控制其水平对齐

<Text style={{paddingTop: 100, textAlign: 'center'}}>Hello World</Text>

只有水平居中了,并没实现垂直居中。 正确的做法是 Text 组件外边包一层 View

<View style={{flex: 1, justifyContent: 'center',  alignItems: 'center'}}>
    <Text>Felix Cao</Text>
</View>

1.3 嵌套

在嵌套的 Text 组件中,子 Text 组件将继承它的父 Text 组件的样式。

<Text style={{paddingTop: 100, fontSize: 18, textAlign: 'center', color: '#712D9C'}}>
   This is the 
   <Text>
     Second  
   </Text>
   section
</Text>

Text 组件能覆盖从父 Text 组件继承而来的样式,也能增加父 Text 组件没有指定的样式。

<Text style={{paddingTop: 100, fontSize: 18, textAlign: 'center', color: '#712D9C'}}>
   This is the 
   <Text style={{fontSize: 28, color: '#ff0000'}}>
     Second  
   </Text>
   section
</Text>

二、Image