美文网首页
React Native 样式

React Native 样式

作者: Mage | 来源:发表于2017-07-04 11:02 被阅读76次

宽高

指定宽高

var styles = StyleSheet.create({  
    view1: {
        height: 100,
        width: 100,
        backgroundColor: 'red',
    }
});

弹性宽高

flex可以使组件在可利用的空间中动态地扩张或收缩。一般会使用flex:1来指定某个组件扩张以撑满所有剩余的空间。如果有多个并列的子组件使用flex:n,则按比例分隔(即占据剩余空间的比等于并列组件间flex值的比)

  render() {
    return (
      // 试试去掉父View中的`flex: 1`。
      // 则父View不再具有尺寸,因此子组件也无法再撑开。
      // 然后再用`height: 300`来代替父View的`flex: 1`试试看?
      // 比例为1:2:3
      <View style={{flex: 1}}>
        <View style={{flex: 1, backgroundColor: 'powderblue'}} />
        <View style={{flex: 2, backgroundColor: 'skyblue'}} />
        <View style={{flex: 3, backgroundColor: 'steelblue'}} />
      </View>
    );
  }

使用Flexbox布局

flex Direction

在组件的style中指定flexDirection可以决定布局的主轴。取值 <column(竖直轴,默认),row(水平轴)>

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>
    );
  }

justify Content

在组件的style中指定justifyContent可以决定其子元素沿着主轴的排列方式。取值:<flex-start(主轴的起始端),center(主轴的中间),flex-end(主轴的末端),space-around(按主轴均匀分布,包括边缘间距),space-between(按主轴均匀分布,不包括边缘间距)>

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>
    );
  }

Align Items

在组件的style中指定alignItems可以决定其子元素沿着次轴(与主轴垂直的轴,比如若主轴方向为row,则次轴方向为column)的排列方式。取值<flex-start(次轴的起始端),center(次轴的中间),flex-end(次轴的末端),stretch(按次轴均匀分布)>

注意:要使stretch选项生效的话,子元素在次轴方向上不能有固定的尺寸。以下面的代码为例:只有将子元素样式中的width: 50去掉之后,alignItems: 'stretch'才能生效。

  render() {
    return (
      // 尝试把`alignItems`改为`flex-start`看看
      // 尝试把`justifyContent`改为`flex-end`看看
      // 尝试把`flexDirection`改为`row`看看
      <View style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
        <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>
    );
  }

相关文章

网友评论

      本文标题:React Native 样式

      本文链接:https://www.haomeiwen.com/subject/bbemwttx.html