React Native
樣式(Style)
在 React Native 中創(chuàng)建樣式儒搭,與在 Web 開發(fā)中使用 CSS 創(chuàng)建樣式十分類似太示,唯一的區(qū)別是樣式屬性名使用了駝峰式命名的寫法弊添,例如,定義一個組件的背景顏色榔至,在 CSS 中屬性名為 background-color
互例,而在 React Native 中則為 backgroundColor
。
要將樣式應(yīng)用在 React Native 組件上这敬,只需要在組件標(biāo)簽上使用 style
屬性航夺,其值可以是一個普通的 Javascript 對象,也可以通過一個 Javascript 對象列表來應(yīng)用多個樣式崔涂。當(dāng)在一個組件上應(yīng)用多個樣式的時候阳掐,后面的樣式會覆蓋前面的樣式,這一點(diǎn)與 CSS 相同堪伍。
例如:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class HelloWorld 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('HelloWorld', () => HelloWorld);
以下是效果圖:
后面的樣式會覆蓋前面沖突的樣式
寬和高(Width & Height)
定義組件的尺寸與其余樣式屬性相似锚烦,同樣是在 style
值的樣式對象中添加相應(yīng)的屬性觅闽,如:
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
export default class HelloWorld extends Component {
render() {
return (
<View>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}}></View>
<View style={{width: 100, height: 100, backgroundColor: 'skyblue'}}></View>
<View style={{width: 150, height: 150, backgroundColor: 'steelblue'}}></View>
</View>
);
}
}
AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);
效果如下:
定義組件的尺寸
使用 Flexbox 布局
接下來說說如何布局屏幕中的各個元素帝雇。
React Native 使用 Flexbox 來進(jìn)行組件的布局,我們將剛剛上面的例子稍加修改:
<View style={{flex: 1}}>
<View style={{flex: 1, backgroundColor: 'powderblue'}} />
<View style={{flex: 2, backgroundColor: 'skyblue'}} />
<View style={{flex: 3, backgroundColor: 'steelblue'}} />
</View>
便可以看到下面的效果:
Flexbox 布局示例
以上只是一個最簡單的示例 Flexbox 在 React Native 和在 CSS 中的工作原理類似蛉拙。只有小小的區(qū)別:
-
flexDirection
屬性的默認(rèn)值為column
而不是row
尸闸。 -
flex
屬性值只支持單個數(shù)字。
更加深入的了解 Flexbox孕锄,可以閱讀 Flexbox