React Native 上手 - 3.样式与布局
2017-02-15 本文已影响0人
范斌
React Native
样式(Style)
在 React Native 中创建样式,与在 Web 开发中使用 CSS 创建样式十分类似,唯一的区别是样式属性名使用了驼峰式命名的写法,例如,定义一个组件的背景颜色,在 CSS 中属性名为 background-color
,而在 React Native 中则为 backgroundColor
。
要将样式应用在 React Native 组件上,只需要在组件标签上使用 style
属性,其值可以是一个普通的 Javascript 对象,也可以通过一个 Javascript 对象列表来应用多个样式。当在一个组件上应用多个样式的时候,后面的样式会覆盖前面的样式,这一点与 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
值的样式对象中添加相应的属性,如:
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 来进行组件的布局,我们将刚刚上面的例子稍加修改:
<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 中的工作原理类似。只有小小的区别:
-
flexDirection
属性的默认值为column
而不是row
。 -
flex
属性值只支持单个数字。
更加深入的了解 Flexbox,可以阅读 Flexbox