rn-8-3. ScrollViewの使い方

ScrollViewでスクロール可能なコンテンツを作る方法を学びます

React Native - 第2章: React Native基礎 - インタラクションとリスト

課題:ScrollViewの使い方を学ぼう

ScrollViewは、画面に入りきらないコンテンツをスクロールできるようにするコンポーネントです。 多くのアイテムをリスト表示してみましょう。

やること

  1. 1.アイテムの配列を作る(10個)
  2. 2.ScrollViewでコンテンツを囲む
  3. 3.mapで各アイテムを表示
  4. 4.各アイテムに背景色と余白を設定

ScrollViewの使い方

ScrollViewをインポートします:

import { View, Text, ScrollView, StyleSheet } from 'react-native';

ScrollViewで囲んでスクロール可能にします:

const items = Array.from({ length: 10 }, (_, i) => i + 1);

<ScrollView>
  {items.map((item) => (
    <View key={item} style={styles.item}>
      <Text>アイテム {item}</Text>
    </View>
  ))}
</ScrollView>

ポイント:ScrollViewは画面に入りきらないコンテンツを表示する時に便利です。アイテム数が多い場合はFlatListの方が効率的です。

期待される出力

┌─────────────┐
│ アイテム 1  │
│ アイテム 2  │
│ アイテム 3  │
│     ⋮       │  ← スクロール可能
│ アイテム10  │
└─────────────┘
import { View, Text, ScrollView, StyleSheet } from 'react-native';

export default function App() {
  // ここに1から10までの配列を作成してください
  // Array.from({ length: 10 }, (_, i) => i + 1) を使います
  
  
  return (
    <View style={styles.container}>
      <Text style={styles.title}>スクロール可能なリスト</Text>
      
      {/* ここにScrollViewを追加してください */}
      {/* その中でitemsをmapして各アイテムを表示 */}
      
        
      {/* </ScrollView> */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  item: {
    backgroundColor: '#E3F2FD',
    padding: 20,
    marginBottom: 10,
    borderRadius: 5,
    borderLeftWidth: 4,
    borderLeftColor: '#2196F3',
  },
  itemText: {
    fontSize: 18,
  },
});