React NativeのUI構築において、スタイル指定の基本となるのがFlexBoxだ。
FlexBoxは複数の要素を縦または横に並べて配置する仕組みで、CSS3でも同様の仕組みが用意されている。
FlexBoxを使えば画面幅の異なることが多いスマホやタブレットで綺麗なUIを動作させることができ、積極的にFlexBoxを使用することが公式に推奨されている。
それではFlexBoxの基本的な使い方を紹介していく。
コンテンツ
Flexを定義する
まず、親要素にFlexを定義することで、その子要素を特定の方向に整列させることができるようになる。
<View style={{
flex: 1,
width: '100%',
}}>
<Image style={{ width: 64, height: 64 }}
source={require('./assets/img01.jpg')}
/>
<Image style={{ width: 64, height: 64 }}
source={require('./assets/img02.jpg')}
/>
<Image style={{ width: 64, height: 64 }}
source={require('./assets/img03.jpg')}
/>
</View>

flexDirection
デフォルトでは縦方向(column)に整列されるようになっているが、ViewのスタイルにflexDirection: ‘row’を指定すると横方向に並べることができる。
<View style={{
flex: 1,
width: '100%',
flexDirection: 'row',
}}>
<Image style={{ width: 64, height: 64 }}
source={require('./assets/img01.jpg')}
/>
<Image style={{ width: 64, height: 64 }}
source={require('./assets/img02.jpg')}
/>
<Image style={{ width: 64, height: 64 }}
source={require('./assets/img03.jpg')}
/>
</View>

justifyContent
子要素の並び方を指定するjustifyContentという属性がある。
デフォルトのflex-startを含め、以下の5種類から指定できる。
flex-start
左上から隙間を開けずに先頭から順に並ぶ。
<View style={{
flex: 1,
width: '100%',
flexDirection: 'row',
justifyContent: 'flex-start',
}}>

center
中心に寄せるように要素を配置する。
<View style={{
flex: 1,
width: '100%',
flexDirection: 'row',
justifyContent: 'center',
}}>

flex-end
flex-startの逆で、画面下に配置される。
<View style={{
flex: 1,
width: '100%',
flexDirection: 'row',
justifyContent: 'flex-end',
}}>

space-around
各要素の余白が等しくなるよう均等配置される。
また、親要素に対しても余白が設定される。
<View style={{
flex: 1,
width: '100%',
flexDirection: 'row',
justifyContent: 'space-around',
}}>

space-between
space-aroundと違い、親要素との間に余白が生じない。
<View style={{
flex: 1,
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
}}>

alignItems
alignItemsでは、flexDirectionで指定した主軸に対し垂直方向の軸に対する要素の並び方を指定する。
例えばflexDirectionにrowを指定して主軸を横方向にした場合、縦方向の要素の並び方を決めることになる。
flex-start
デフォルトではflex-startの設定になっており、隙間を空けずに左上から順に並ぶ。
<View style={{
flex: 1,
width: '100%',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'flex-start',
}}>

flex-end
右下方向から並ぶ。要素の順番は変わらない。
<View style={{
flex: 1,
width: '100%',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'flex-end',
}}>

center
実際のUI構築で最も使うことの多いのがcenterだろう。
要素を中央寄せに配置する。
<View style={{
flex: 1,
width: '100%',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}}>

stretch
FlexBoxの要素の軸方向の幅を指定していない場合、親要素の幅に子要素を合わせることができる。
例として、flexDirectionにcolumnを指定した場合、横方向の幅を可能な限り大きくすることができる。
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'stretch',
}}>
<View style={{height: 50, backgroundColor: 'powderblue'}} />
<View style={{height: 50, backgroundColor: 'skyblue'}} />
<View style={{height: 50, backgroundColor: 'steelblue'}} />
</View>
