rn-7-4. Flexboxレイアウト(横方向)

Flexboxで横方向のレイアウトとflex比率を学びます

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

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

flexDirection: 'row'を使うと、要素を横に並べられます。 また、flexプロパティで幅の比率を指定できます。

やること

  1. 1.3つのボックスを横に並べる
  2. 2.コンテナでflexDirection: 'row'を設定
  3. 3.Box1とBox3はflex: 1、Box2はflex: 2
  4. 4.各ボックスに異なる背景色と高さ

横方向レイアウトとflex比率

flexDirection: 'row'で横並びにします:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',  // 横方向
    justifyContent: 'center',
    alignItems: 'center',
  },
});

flexプロパティで幅の比率を指定します:

box1: {
  flex: 1,  // 比率1
  height: 100,
},
box2: {
  flex: 2,  // 比率2(box1の2倍の幅)
  height: 150,
},
box3: {
  flex: 1,  // 比率1
  height: 100,
}

この場合、画面幅を4等分して、Box1が1/4、Box2が2/4(半分)、Box3が1/4の幅になります。

ポイント:flexDirection: 'row'で横並びに、flexで幅の比率を調整します。

期待される出力

┌────┬──────────┬────┐
│    │          │    │
│Box1│   Box2   │Box3│
│    │          │    │
└────┴──────────┴────┘
 1      2          1
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
    // flexDirection: 'row'で横並びに
    // justifyContent: 'center'
    // alignItems: 'center'
    
  },
  box1: {
    // flex: 1 (幅の比率)
    // height: 100
    // backgroundColor: '#FF5252' (赤)
    // justifyContent: 'center'
    // alignItems: 'center'
    
  },
  box2: {
    // flex: 2 (幅の比率 - box1の2倍)
    // height: 150
    // backgroundColor: '#4CAF50' (緑)
    // justifyContent: 'center'
    // alignItems: 'center'
    
  },
  box3: {
    // flex: 1 (幅の比率)
    // height: 100
    // backgroundColor: '#2196F3' (青)
    // justifyContent: 'center'
    // alignItems: 'center'
    
  },
  boxText: {
    color: 'white',
    fontWeight: 'bold',
  },
});