React Native③ カウンターを作る~通常~

まずシンプルに作成

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button } from 'react-native';
import {useState} from 'react';

export default function App() {
  const [count, setCount] = useState(0);
  const increaseCount = () =>{
    setCount((count) => count + 1);
  }
  return (
    <View style={styles.container}>
      <Text>Counter</Text>
      <Text>{count}</Text>
      <Button title="+"
              onPress={increaseCount}
      />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

次に、今後の応用を見据え、親子コンポーネントで作成してみます。

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button } from 'react-native';
import {useState} from 'react';

function SubCounter(props){
  const increaseCount = () =>{
    props.inc();
  }
  return(
    <View>
       <Text>{props.count}</Text>
       <Button title='+'
              onPress={increaseCount}
       />
    </View>
  )
}

export default function App() {
  const [count, setCount] = useState(0);
  const increaseCount = () =>{
    setCount((count) => count + 1);
  }
  return (
    <View style={styles.container}>
      <Text>Counter</Text>
      <SubCounter inc={increaseCount}
                  count={count}
      />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
 
車の台数と歩行者数をそれぞれ測定できるようにする。
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button } from 'react-native';
import {useState} from 'react';

function SubCounter(props){
  const increaseCount = () =>{
    props.inc();
  }
  return(
    <View>
       <Text>{props.title}</Text>
       <Text>{props.count}</Text>
       <Button title='+'
              onPress={increaseCount}
       />
    </View>
  )
}

export default function App() {
  const [count, setCount] = useState(0);
  const [count2, setCount2] = useState(0);
  const increaseCount = () =>{
    setCount((count) => count + 1);
  }
  const increaseCount2 = () =>{
    setCount2((count2) => count2 +1)
  }
  return (
    <View style={styles.container}>
      <Text style={{fontSize: 20}}>Counter</Text>
      <SubCounter inc={increaseCount}
                  title="車の台数"
                  count={count}
      />
      <SubCounter inc={increaseCount2}
                  title="歩行者数"
                  count={count2}
      />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});