rn-7-3. Flexboxレイアウト(縦方向)

Flexboxで縦方向のレイアウトを学びます

React Native - 第1章: React Native基礎 - コンポーネントとスタイリング

課題:Flexboxレイアウト(縦方向)を学ぼう

React NativeのレイアウトはFlexboxを使います。 縦方向に要素を並べて、配置を調整してみましょう。

やること

  1. 1.3つのボックスを作る
  2. 2.コンテナでjustifyContent: 'center'を設定
  3. 3.alignItems: 'center'で左右中央に
  4. 4.各ボックスに異なる背景色(赤、緑、青)

Flexboxの基本

主なFlexboxプロパティ:

  • flexDirection: 並べる方向('column'は縦、'row'は横)
  • justifyContent: 主軸方向の配置('center', 'flex-start', 'flex-end', 'space-between'など)
  • alignItems: 交差軸方向の配置('center', 'flex-start', 'flex-end'など)
const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',  // 縦方向(デフォルト)
    justifyContent: 'center', // 上下中央
    alignItems: 'center',     // 左右中央
  },
  box: {
    width: 100,
    height: 100,
    margin: 10,
  },
});

ポイント:flex: 1で画面いっぱいに広がります。 justifyContentとalignItemsで配置を調整します。

期待される出力

        ┌──────┐
        │ Box1 │  ← 赤
        └──────┘
        
        ┌──────┐
        │ Box2 │  ← 緑
        └──────┘
        
        ┌──────┐
        │ Box3 │  ← 青
        └──────┘
import { View, Text, StyleSheet } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.box1}>
        <Text style={styles.boxText}>Box 1</Text>
      </View>
      <View style={styles.box2}>
        <Text style={styles.boxText}>Box 2</Text>
      </View>
      <View style={styles.box3}>
        <Text style={styles.boxText}>Box 3</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    // flex: 1で画面いっぱいに
    // justifyContent: 'center'で上下中央
    // alignItems: 'center'で左右中央
    
  },
  box1: {
    width: 100,
    height: 100,
    // backgroundColor: '#FF5252' (赤)
    // justifyContent: 'center'
    // alignItems: 'center'
    // margin: 10
    
  },
  box2: {
    width: 100,
    height: 100,
    // backgroundColor: '#4CAF50' (緑)
    // justifyContent: 'center'
    // alignItems: 'center'
    // margin: 10
    
  },
  box3: {
    width: 100,
    height: 100,
    // backgroundColor: '#2196F3' (青)
    // justifyContent: 'center'
    // alignItems: 'center'
    // margin: 10
    
  },
  boxText: {
    color: 'white',
    fontWeight: 'bold',
  },
});