React-native 에서 숫자 카운트를 세는 프로그램을 만들어 보겠다.
app.js에 이렇게 적고
import {View, StyleSheet } from 'react-native';
import {useState} from 'react'
// 플러스 카운트 버튼
import PlusCount from './components/PlusCount'
// 마이너스 카운트 버튼
import MinusCount from './components/MinusCount'
// 숫자가 출력될 컴포넌트
import PrintNum from './components/PrintNum'
export default function App() {
const [countNum,setCountNum] = useState(0)
const plus = () => {
setCountNum(countNum+1)
}
const minus = () => {
setCountNum(countNum-1)
}
const zero = () => { // 초기화 함수
setCountNum(0)
}
return (
<View style={styles.container} >
<PlusCount plus = {plus} />
<View style={styles.space}/>
<PrintNum countNum = {countNum} zero = {zero}/>
<View style={styles.space}/>
<MinusCount minus = {minus} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
space: {
height: 30,
}
})
숫자를 증가시킬 plus 컴포넌트
import { View, StyleSheet, Button } from 'react-native';
const PlusCount = (props) => (
<View>
<Button
title='Plus'
onPress = {() => props.plus()}
style = {styles.button}
/>
</View>
)
const styles = StyleSheet.create({
button: {
alignItems: 'center',
justifyContent: 'center',
width: 100,
height: 100,
marginBottom: 30,
borderRadius: 35,
},
});
export default PlusCount
app에서 숫자를 증가시키는 함수를 넘겨받아 props로 호출하여 사용한다.
숫자를 감소시키는 minus 컴포넌트
import { Text, View, StyleSheet, Button } from 'react-native';
const MinusCount = (props) => (
<View>
<Button
title='Minus'
onPress = {() => props.minus()}
/>
</View>
)
export default MinusCount
app에서 숫자를 감소시키는 함수를 넘겨받아 props로 호출하여 사용한다.
숫자를 출력하는 컴포넌트
import { Text, View, StyleSheet, Button,TouchableOpacity } from 'react-native';
const PrintNum = (props) => (
<View>
<TouchableOpacity
onPress = { () => props.zero()}
>
<Text style = {styles.text}>
{props.countNum}
</Text>
</TouchableOpacity>
</View>
)
const styles = StyleSheet.create({
text: {
fontSize: 100,
textAlign: 'center',
}
});
export default PrintNum
숫자를 text로 출력하고 숫자가 클릭되면 숫자를 초기화 하는 함수를 넘겨받아 사용한다.
실행 시킨 모습이다.
'react, react-native' 카테고리의 다른 글
React Native 카카오 간편 로그인 구현 (0) | 2023.04.15 |
---|---|
Map, ScrollView, TextInput (0) | 2023.04.11 |
TochableOpacity, Button (0) | 2023.04.11 |
State, Props (0) | 2023.04.11 |
React Style 적용 방법 (0) | 2023.04.11 |