樣式
原文地址,
原文地址2,本文為原文不完全翻譯
在ReactNative,是通過使用JavaScript來設(shè)置樣式的,全部的核心組件都擁有style這個屬性,這些樣式的名字和值都和CSS一一對應(yīng),唯一的不同就是ReactNative使用的是駝峰命名,如backgroundColor而不是background_color.
style屬性和JavaScript是一樣的,下面的例子就是style的簡單使用,可以見到style是可以接收一個數(shù)組的,不過這時候數(shù)組的最后一個成員擁有最高優(yōu)先權(quán),所以你可以利用這個特性來集成與改寫style
為了代碼的整潔性,一般都是使用StyleSheet.create方法在一個地方定義好幾個style
import React, { Component } from 'react';
import {AppRegistry, StyleSheet,Text, View} from 'react-native';
class alotStyles extends Component {
render(){
return (
<View>
<Text style={styles.red}>justred</Text>
<Text style={styles.bigred}>bigred</Text>
<Text style={styles.bigblue}>bigblue</Text>
<Text style={styles.red,styles.bigblue,styles.blue}>mixture</Text>
</View>
)
}
}
const styles = StyleSheet.create({
red:{
color:'#FF0000'
},
blue:{
color:'#0000FF'
},
bigred:{
color:'#FF0000',
fontSize:30,
fontWeight:'bold'
},
bigblue:{
color:'#0000FF',
fontSize:30,
fontWeight:'bold'
},
})
AppRegistry.registerComponent('alotStyles',()=>alotStyles);

Paste_Image.png
寬與高
一個組件的寬與高決定了組件在屏幕上面的尺寸
固定尺寸
控制組件位置最簡單的方式就是給它一個固定的寬高,ReactNative的組件尺寸單位是dip(設(shè)備無關(guān)像素)
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);

Paste_Image.png
這種寫法只適用于尺寸在各個大小不同的手機(jī)屏幕上都一樣的情況,所以用得不多.
可變尺寸
適用屬性flex可以讓組件在一個有效的空間內(nèi)按比例縮放,一般情況下我們賦值flex=1,這意味著讓組件盡可能地填充有效空間,并且根據(jù)在同一個父控件中的兄弟控件的flex的值等比例分配空間
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
class FlexDimensionsBasics extends Component{
render(){
return(<View style={{height:100, width:100}}>
<View style={{flex:1, backgroundColor: 'powderblue'}} />
<View style={{flex:1, backgroundColor: 'skyblue'}} />
<View style={{flex:1, backgroundColor: 'steelblue'}} />
</View>)
}
}
AppRegistry.registerComponent('FlexDimensionsBasics', () => FlexDimensionsBasics);

Paste_Image.png