Expo - Counter 생성

MOON·2020년 7월 23일
0

Counter Button

이번에는 useState 를 통해
컴포넌트에서 바뀌는 값 관리할 수 있는,
흔히들 많이 연습해보는 Counter를 만들어 보았다.


import React, { useState } from "react";
 .
 .
 
const Counter = () => {
  const [count, setCount] = useState(0);
  
  const onIncrease = () => 
  setCount(prevCount => prevCount + 1);
  
  const onDecrease = () =>
  setCount(prevCount => prevCount - 1);
  
  const Reset = () => setCount(prevCount => 0);
   
   return(
   	//*own code*//
    );
   };
 
 export default Counter;
  

+1을 증가 시켜줄 onIncrease 함수,
-1을 감소 시켜줄 onDecrease 함수,
0으로 리셋 시켜줄 onReset 함수를 만들었다.


return (
    <View style={styles.container}>
      <View style={styles.countContainer}>
        <Text>수량: {count}</Text>
      </View>
      <TouchableOpacity
        style={styles.button}
        activeOpacity={0.7}
        onPress={onIncrease}
      >
        <Text>+1</Text>
      </TouchableOpacity>
       <TouchableOpacity
        activeOpacity={0.7}
        style={styles.button}
        onPress={onDecrease}
      >
        <Text>-1</Text>
      </TouchableOpacity>
      <TouchableOpacity
        activeOpacity={0.7}
        style={styles.button}
        onPress={Reset}
      >
        <Text>reset</Text>
      </TouchableOpacity>
    </View>
  );
};

이제 Text이름과 알맞게 TouchableOpacity onPress 안에 함수들을 넣어준다.


Counter CSS

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingHorizontal: 10,
  },
  button: {
    alignItems: "center",
    backgroundColor: "#DDDDDD",
    padding: 10,
    margin: 3,
   
  },
  countContainer: {
    alignItems: "center",
    padding: 10,
  }
});

0개의 댓글