樣式
使用React Native,您不需要使用特殊語言或語法來定義樣式。您只需使用JavaScript設計應用程序。所有的核心組件都接受一個名字命名style。樣式名稱和值通常與CSS在CSS上的工作方式相匹配,除了使用駝峰命名,backgroundColor而不是background-color。
style 可以是一個普通的JavaScript對象,還可以傳遞一個樣式數組-數組中的最后一個樣式為最高優先級,因此可以使用繼承樣式。
需要引入一個新的 ** StyleSheet **
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
class LotsOfStyles extends Component {
render() {
return (
<View>
<Text style={styles.red}>just red</Text>
<Text style={styles.bigblue}>just bigblue</Text>
<Text style={[styles.bigblue, styles.red]}>bigblue, then red</Text>
<Text style={[styles.red, styles.bigblue]}>red, then bigblue</Text>
</View>
);
}
}
const styles = StyleSheet.create({
bigblue: {
color: 'blue',
fontWeight: 'bold',
fontSize: 30,
},
red: {
color: 'red',
},
});
AppRegistry.registerComponent('AwesomeProject', () => LotsOfStyles);
看起來像這樣
更多樣式以后可以參考文檔
facebook: Text組件實現
China: Text組件實現 For China
Frame (寬高)
固定尺寸
設置組件尺寸的最簡單的方法是添加一個固定width和height樣式。React Native中的所有尺寸都是無單位的,并且表示密度無關的像素。
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
class FixedDimensionsBasics extends Component {
render() {
return (
<View>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 100, height: 100, backgroundColor: 'skyblue'}} />
<View style={{width: 150, height: 150, backgroundColor: 'steelblue'}} />
</View>
);
}
}
AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);
以這種方式設置尺寸對于總是以完全相同的大小渲染的組件而言,與屏幕尺寸無關。
Flex組件
使組件根據可用空間動態擴展和縮小。通常,您將使用flex: 1它來告訴組件填充所有可用空間,并在同一個父項之間在每個其他組件之間均勻分配。空間的分量將采取相比
如果一個組件的父對象的維數大于0,則該組件只能擴展為填充可用空間。如果父項沒有固定的width,height或者flex父對象的維度為0,并且flex子控件將不可見。
舉個例子
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
class FlexDimensionsBasics extends Component {
render() {
return (
// Try removing the `flex: 1` on the parent View.
// The parent will not have dimensions, so the children can't expand.
// What if you add `height: 300` instead of `flex: 1`?
<View style={{flex: 1}}>
<View style={{flex: 1, backgroundColor: 'powderblue'}} />
<View style={{flex: 2, backgroundColor: 'skyblue'}} />
<View style={{flex: 3, backgroundColor: 'steelblue'}} />
</View>
);
}
}
AppRegistry.registerComponent('AwesomeProject', () => FlexDimensionsBasics);