rn-8-2. ButtonとTouchableOpacity

ButtonとTouchableOpacityの使い方を学びます

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

課題:ButtonとTouchableOpacityを学ぼう

React Nativeには、ボタンを作る方法が2つあります。Buttonはシンプルな標準ボタン、TouchableOpacityはカスタマイズ可能なボタンです。

やること

  1. 1.カウンターの状態を作る(初期値: 0)
  2. 2.Buttonで+1する機能を作る
  3. 3.TouchableOpacityで-1する機能を作る
  4. 4.リセットボタンも追加

ButtonとTouchableOpacityの使い方

インポートします:

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

Buttonの使い方:

<Button 
  title="+1"
  onPress={() => setCount(count + 1)}
/>

TouchableOpacityの使い方:

<TouchableOpacity 
  style={styles.button}
  onPress={() => setCount(count - 1)}
>
  <Text style={styles.buttonText}>-1</Text>
</TouchableOpacity>

ポイント:Buttonはシンプルですが、TouchableOpacityは自由にスタイルを設定できます。

期待される出力

カウント: 5

[+1] [-1] [リセット]
import { View, Text, Button, TouchableOpacity, StyleSheet } from 'react-native';
import { useState } from 'react';

export default function App() {
  // ここにcountの状態を作成してください(初期値: 0)
  
  
  return (
    <View style={styles.container}>
      <Text style={styles.count}>カウント: {/* ここにcountを表示 */}</Text>
      
      <View style={styles.buttonContainer}>
        {/* ここにButtonで+1ボタンを追加 */}
        
        
        {/* ここにTouchableOpacityで-1ボタンを追加 */}
        <TouchableOpacity 
          style={styles.customButton}
        >
          <Text style={styles.buttonText}>-1</Text>
        </TouchableOpacity>
        
        {/* ここにButtonでリセットボタンを追加 */}
        
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  count: {
    fontSize: 48,
    fontWeight: 'bold',
    marginBottom: 30,
  },
  buttonContainer: {
    flexDirection: 'row',
    gap: 10,
  },
  customButton: {
    backgroundColor: '#FF5252',
    padding: 15,
    borderRadius: 5,
    minWidth: 60,
    alignItems: 'center',
  },
  buttonText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
});