所有的核心组件都接受名为style的属性,这些样式名基本上是遵循web上的css的命名,只是按照js的语法要求使用驼峰命名法,例如将background-clor改为backgroundColor。
在实际开发中组件的样式会越来越复杂,我们建议使用StyleSheet.create来集中定义组件的样式。
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
export default 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',
},
});
flexbox
我们在React Native中使用flexbox规则来指定某个组件的子元素的布局,flexbox可以在不同屏幕尺寸上提供一致的布局结构。
一般来说,使用flexDirection alignItems和justifyContent三个样式属性就已经满足大多数局需求。
1.flex direction
在组件的style中指定的flexDirection可以决定布局的主轴,子元素是应该沿着水平轴(row)方向排列,还是沿着竖直轴(column)方向排列呢?默认值是坚直轴(column)方向。
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
export default class FlexDirectionBasics extends Component {
render() {
return (
// 尝试把`flexDirection`改为`column`看看
<View style={{flex: 1, flexDirection: 'row'}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
</View>
);
}
};
2.justify content
在组件的style中指定justiryContent可以决定其子元素沿着主轴的排列方式,子元素是应该靠近主轴的起端还是末端分布。对应的这些可选项有flex-start, flex-end , center, space-around, space-between, space-evenly.
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
export default class JustifyContentBasics extends Component {
render() {
return (
// 尝试把`justifyContent`改为`center`看看
// 尝试把`flexDirection`改为`row`看看
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
</View>
);
}
};
3.align items
可以决定子元素沿着次轴的排列方式,子元素是应该靠近次轴的起始端还是末端。可选项:flex-start, center, flex-end , stretch.
最后欢迎大家访问我的个人网站:1024s