《ReactNative系列講義》基礎篇---06.Layout and Flexbox

| 版權聲明:本文爲博主原創文章,未經博主允許不得轉載。

一、簡介

上一篇中介紹了組件尺寸的定義方式,今天聊聊組件位置的定義方式。首先是在父組件中確定子組件的佈局方式,然後選擇子組件在主軸上的排列方式和次軸的排列方式。Flexbox的設計初衷是爲了使佈局適應不同尺寸的屏幕。除個別例外,其他的方面都和CSS中的思想保持一致。

二、基礎知識

  • flexDirection:決定主軸的佈局方式;兩種佈局方式:橫向(row)和縱向(column);默認是縱向,這也是和CSS中不同的方面之一。
  • justifyContent:決定子元素在主軸上的分佈樣式;五種樣式:flex-start, center, flex-end, space-around, space-between
  • alignItems:決定子元素在次軸上的分佈方式;四種樣式:flex-start, center, flex-end, stretch(注:使用stretch屬性時,子組件在次軸上不能有固定的尺寸)
  • flex:只支持單個號碼;這也是和CSS的不同之處。

三、應用

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

export default class JustifyContentBasics extends Component {
  render() {
    return (
      // 主軸方向是縱向
      // 在縱向方向子元素均分主軸屏幕的可見長度
      <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>
    );
  }
};
  • justifyContent: flex-start 主軸的起點
  • justifyContent: center 主軸的中心
  • justifyContent: flex-end 主軸的末尾
  • justifyContent: space-around 延主軸方向子元素左右等距分佈
  • justifyContent: space-between 延主軸方向均分主軸
import React, { Component } from 'react';
import { View } from 'react-native';

export default class AlignItemsBasics extends Component {
  render() {
    return (
      // 主軸方向是縱向
      // 主軸方向居中
      // 次軸方向居中
      // 最終效果:所有的子元素聚集在屏幕中央
      <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>
    );
  }
};
  • alignItems: flex-start 次軸的起點
  • alignItems: center 次軸的中心
  • alignItems: flex-end 次軸的末尾
  • alignItems: stretch 延伸,即充滿可充滿的空間,有些類似flex,不過stretch更加靈活;該屬性在使用的時候不可在次軸方向設置該子元素的寬度
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章