ReactNative学习笔记5

原文地址,本文为原文不完全翻译

布局与可变框

一个组件可以根据可变框计算来确定它的子组件的位置,可边框的作用是用来适配不尺寸的手机屏幕局的.
你通常需要结合flexDirection, alignItems, 和 justifyContent 来实现想要的布局.

flexDirection

控制子组件排列方向,水平方向排列赋值row,竖直方向排列赋值column,默认值为column

import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';

class FlexDirectionBasics extends Component{
  render(){
    return(
      <View style={{flex:1,flexDirection: 'row'}}>
        <View style={{flex:1, height: 50, backgroundColor: '#FF0000'}}/>
        <View style={{flex:1, height: 50, backgroundColor: '#00FF00'}}/>
        <View style={{flex:1, height: 50, backgroundColor: '#0000FF'}}/>
      </View>
    );
  }
}

AppRegistry.registerComponent('FlexDirectionBasics', ()=>FlexDirectionBasics)
Paste_Image.png
Justify Content

这个属性决定了子组件的分布方式,分布的方式有: flex-start(挤压在其实位置), center(挤压在中间), flex-end(挤压在底部), space-around(边缘分布均分), 和 space-between(均分并居中).

import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';

class justyContentDemo extends Component{
  render(){
      return(
        //尝试各种不同的值,加深理解(如:flex-start, center, flex-end)
        <View style={{ 
           flex: 1,
           flexDirection: 'column',
           justifyContent: 'space-between',
        }}>
            <View style={{width:50,height:50,backgroundColor:'#00FF00'}}/>
            <View style={{width:50,height:50,backgroundColor:'#FF0000'}}/>
            <View style={{width:50,height:50,backgroundColor:'#0000FF'}}/>
        </View>
      );
  }
}

AppRegistry.registerComponent('justyContentDemo', ()=>justyContentDemo);
Paste_Image.png
Align Items

style中添加alignItems属性可以影响子控件在父控件中的相对位置(是flex-start(顶部), center(居中), flex-end(底部), 还是拉伸填充(stretch)),假如子组件是水平排列就是影响竖直方向的相对位置,假如子组件是竖直排列影响的就是水平方向的相对位置,另外alignItems的优先级是低于宽高的,假如发生冲突的话,宽高设置才是有效的,比如下面的例子中,子组件水平排列,设置alignItems : 'stretch' , 但是因为蓝色与绿色的组件设置了height:50,所以无效,只有红色的组件有效发生了拉伸填充

import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';

class AlignItemsBasics extends Component {
  render(){
    return(
      <View style={{
            flex:1,
            flexDirection:'row',
            justifyContent:'center',
            alignItems: 'stretch'
      }}>
        <View style={{width: 50, backgroundColor: 'red'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'blue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'green'}} />
      </View>
    )
  }
}

AppRegistry.registerComponent('AlignItemsBasics', ()=>AlignItemsBasics);
Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容