React-Native入门指南

    二、使用CSS样式 & Flexbox布局

    1. 1、基本样式
    2. 这里使用ViewText组件作为演示对象,首先,修改index.ios.js里面的代码,这里只需要关注StyleSheetrender里面的模板。修改后的代码如下:
    3. /**
    4. * Sample React Native App
    5. * https://github.com/facebook/react-native
    6. */
    7. 'use strict';
    8. var React = require('react-native');
    9. var {
    10. AppRegistry,
    11. StyleSheet,
    12. Text,
    13. View,
    14. } = React;
    15. var HelloWorld = React.createClass({
    16. render: function() {
    17. return (
    18. <View>
    19. <View></View>
    20. </View>
    21. }
    22. });
    23. var styles = StyleSheet.create({
    24. });
    25. AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
    26. 这时候,你cmd + R刷新模拟器应该看到是空白的界面。现在,是展现css魅力的时候了。React-native使用的css 表达是一个JS自面量对象,并且严格区分该对象属性的类型,所以要遵循对象的写法,而不能使用以前css的写法,这个需要自己熟悉了。
    27. 1)增加一个带边框的矩形,红色边框
    28. 直接在组件上添加样式是这样的:style={{height:40, borderWidth: 1, borderColor: 'red'}}style是组件的一个自有属性,第一个{}JS执行环境或者说是模板,第二个{}只是css样式对象的括号而已(慢慢体会,不难理解)。这样修改后的代码如下:
    29. render: function() {
    30. return (
    31. <View>
    32. <View style={{height:40, borderWidth: 1, borderColor: 'red'}}>
    33. </View>
    34. </View>
    35. );
    36. }
    37. cmd R刷新模拟器,结果如下:

    基本css

    1. 3)独立样式类
    2. 其实上面已经展示了独立样式类了,那么样式类创建很简单,我们只需要使用React.StyleSheet来创建类。其实创建的类就是一个js对象而已。那么在组件上引用是这样的<View style={{对象名称.对象属性}}></View>,就跟上面(2)的代码一样。
    3. 2、说说Flexbox布局
    4. 其实,这样的css样式,作为web开发者一用就会,那么说说布局的事儿。除去margin, padding, position等大家熟悉的web布局的话,最为重要的就是flexbox,目前支持的属性如下,有6个:

    1. (1)先说flex属性,上一段代码
    2. render: function() {
    3. <View style={styles.style_0}>
    4. <View style={styles.style_1}></View>
    5. <View style={styles.style_1}></View>
    6. <View style={{flex:10}}></View>
    7. </View>
    8. );
    9. }
    10. });
    11. var styles = StyleSheet.create({
    12. style_0:{
    13. flex:1,
    14. },
    15. style_1:{
    16. flex: 5,
    17. height:40,
    18. borderWidth: 1,
    19. borderColor: 'red',
    20. }
    21. });
    22. 当一个(元素)组件,定义了flex属性时,表示该元素是可伸缩的。当然flex的属性值是大于0的时候才伸缩,其小于和等于0的时候不伸缩,例如:flex:0, flex:-1等。上面的代码,最外层的view是可伸缩的,因为没有兄弟节点和它抢占空间。里层是3view,可以看到三个viewflex属性加起来是5+5+10=20,所以第一个view和第二个view分别占14伸缩空间, 最后一个view占据12空间,具体如下图:

    flex

    1. (3)alignSelf:对齐方式
    2. alignSelf的对齐方式主要有四种:flex-start flex-end center auto stretch。看看代码,应该就很清楚了:

    1. 效果如下图

    flex