6. 카운터 만들기

서창용·2022년 3월 2일
0
  1. UI준비
  • 배경색 전체로 하기
const styles = StyleSheet.create({
  full: {
    flex: 1,
  },
});
  1. 최종 js
  • Counter.js
import React from 'react';
import {View, Text, StyleSheet, Button} from 'react-native';

function Counter({count, onIncrease, onDecrease}) {
  return (
    <View style={styles.wrapper}>
      <View style={styles.numberArea}>
        <Text style={styles.number}>{count}</Text>
      </View>
      <Button title="+1" onPress={onIncrease} />
      <Button title="-1" onPress={onDecrease} />
    </View>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    flex: 1,
  },
  numberArea: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  number: {
    fontSize: 72,
    fontWeight: 'bold',
  },
});

export default Counter;
  • app.js
import React, {useState} from 'react';
import {SafeAreaView, StyleSheet} from 'react-native';
import Counter from './componets/Counter';

const App = () => {
  const [count, setCount] = useState(0);

  const onIncrease = () => setCount(count + 1);
  const onDecrease = () => setCount(count - 1);

  return (
    <SafeAreaView style={styles.full}>
      <Counter count={count} onIncrease={onIncrease} onDecrease={onDecrease} />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  full: {
    flex: 1,
  },
});

export default App;

useState를 사용할때 기본값으로 숫자 타입 0을 지정

const {count, setCount} = useState(0);

그리고 이 값을 변경하는 +,-함수

const onIncrease = () => setCount(count + 1);
const onDecrease = () => setCount(count - 1);

이 함수를 Counter 컴퍼넌트에 props로 전달

<Counter count={count} onIncrease={onIncrease} onDecrease={onDecrease}/>

잘됨!

profile
관신분야 : 브랜딩, 마케팅, 파이썬, 리액트 네이티브, MSA, 엘라스틱서치

0개의 댓글