Mobile 개발/RN Project - Realty Reg.

RN Prj - project 에 state 적용

히핑소 2020. 7. 5. 21:36
반응형

7일자 to do app 에 적용해본 useState Component 를

등기계산기 project 에 적용해보겠습니다.

 

오늘 coding Output 은 Calculator 에서 '거래금액' 과 '공시지가',

그리고 '채권매도할인율' 을 입력하고 '계산하기' Button Component 를 클릭하면

채권, 수입인지, 취득세, 등기총비용에 값이 적용되도록 하는 것.

 

계산하기 누르면 등기비용 계산

 

먼저 각 금액 별 useState Component instance 를 만들고

calculateHandler() 로 input 값을 output 창에 write.

우선 값을 대충 쓰지만, 추 후에 제대로 된 값이 입력 되도록 수정 진행.

 

const 상수인 bondPrice 는 위에서 useState(초기화깂) 으로 0이 되었기 때문에

처음 app 실행 시 {bondPrice} 원 => 0 원 으로 보여지고

이 후 bondPrice 값은 calculateHandler() :: setBondPrice() 통해 값이 변경.

 

 

전체 코드 [CalculatorTab.js]

import React, {useState} from 'react';
import { StyleSheet, Button, Text, View, TextInput, FlatList, TouchableWithoutFeedback } from 'react-native';
import { createStackNavigator } from '@react-navigation/stack';
import CalculateManager from './CalculateManager';

  function DiscountDetailsScreen() {
    return (
      <View style={styles.container}>
        <Text>the of Discount Rate</Text>
        <Text>CalculateManager()</Text>
      </View>
    );
  }

  function CalculatorScreen({ navigation }) {
    
    const fontStyles = ["방문", "이폼", "전자"];
    const [fontStyleIdx, setFontStyleIdx] = useState(0);

    const [buyingValue, onChangeBuyingValue] = useState(0);
    const [officialValue, onChangeOfficialValue] = useState(0);
    const [sellRate, onChangeSellRate] = useState(0);

    const [bondPrice, setBondPrice] = useState(0);
    const [incomePrice, setIncomePrice] = useState(0);
    const [homeTax, setHomeTax] = useState({rate:0, price:0});

    const calculateHandler = () => {
      setBondPrice(buyingValue);
      setIncomePrice(officialValue);
      setHomeTax({rate:3.5, price:buyingValue - officialValue});

        //공시지가 public int calculateBondPrice(long price, boolean residenceOfCity, int category) {
        //공시지가     int finalBondPurchase(long price) {
        //매입금액, 수입인지     public int calculateIncome(long price) {
        //매입금액, 취득세     public void calculateHometax(

        //상속/증여   public int calculateFreeTax(long realPrice, long giveDeduction) {

        //    public float getTotalRate() {
        //public float getSpecialRate() {
        //public float getLocalEduRate() { return mLocalEduRate / 10; }
        //public float getTaxRate() { return mTaxRate / 10; }
    }

    return (
      <View style={styles.container}>
        <View style={styles.rowContainerCheckBox}>
          <Text style={styles.textBoldLeft}>등기 수수료 납부</Text>          
          <CustomPicker
            data={fontStyles}
            currentIndex={fontStyleIdx}
            onSelected={setFontStyleIdx}
          />
        </View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBoldLeft}>거래금액 입력</Text>
          <TextInput
            placeholder='0'
            keyboardType={'number-pad'}
            returnKeyType='done'
            style={{width:100,  padding:5, textAlign:'right'}}
            onChangeText={text => onChangeBuyingValue(text)}
            value={buyingValue}
          />
          <Text style={styles.textBasicLeft}>만원</Text>
        </View>
        

        <View style={styles.rowContainer}>
          <Text style={styles.textBoldLeft}>공시지가 입력</Text>
          <TextInput
            placeholder='0'
            keyboardType={'number-pad'}
            returnKeyType='done'
            style={{padding:5, textAlign:'right'}}
            onChangeText={text => onChangeOfficialValue(text)}
            value={officialValue}
          />
          <Text style={styles.textBasicLeft}>만원</Text>
          <Button
            title="계산하기"
            color='#f0f'
            onPress={calculateHandler}
          />
        </View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBoldLeft}>공시지가 확인</Text>
          <Button
            title="국토교통부 가격열람"
            onPress={() => navigation.navigate('DiscountDetails')}
          />
        </View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBoldLeft}>채권매도할인율 입력</Text>
          <TextInput
            placeholder='0'
            keyboardType={'numeric'}
            returnKeyType='done'
            style={{padding:5, textAlign:'right'}}
            onChangeText={text => onChangeSellRate(text)}
            value={sellRate}
          />
          <Button
            title="할인률 조회"
            onPress={() => navigation.navigate('DiscountDetails')}
          />
        </View>

        <View style={styles.divider}></View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBoldLeft}>국민주택채권매입</Text>          
          <Text style={styles.textBoldRight}>{bondPrice} 원</Text>
        </View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBoldLeft}>수입인지</Text>
          <Text style={styles.textBoldRight}>{incomePrice} 원</Text>
        </View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBoldLeft}>등기수수료</Text>
          <Text style={styles.textBoldRight}>15000 원</Text>
        </View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBoldWidth}>취득세합계</Text>
          <Text style={styles.textBoldWidth}>({homeTax.rate}%)</Text>
          <Text style={styles.textBoldRight}>{homeTax.price} 원</Text>
        </View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBasicWdith}>취득세</Text>
          <Text style={styles.textBasicWdith}>(3.5%)</Text>
          <Text style={styles.textBoldRight}>0 원</Text>
        </View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBasicWdith}>지방교육세</Text>
          <Text style={styles.textBasicWdith}>(0.3%)</Text>
          <Text style={styles.textBoldRight}>0 원</Text>
        </View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBasicWdith}>농어촌특별세</Text>
          <Text style={styles.textBasicWdith}>(0.0%)</Text>
          <Text style={styles.textBoldRight}>0 원</Text>
        </View>

        <View style={styles.rowContainer}>
          <Text style={styles.textBoldLeft}>총등기비용</Text>          
          <Text style={styles.textBoldRight}>0 원</Text>
        </View>

      </View>
    );
  }

  function CustomPicker({ label, data, currentIndex, onSelected }) {
    return (
      <>
        <Text style={styles.title}>{label}</Text>
        <View style={styles.wrapperHorizontal}>
          <FlatList
            bounces
            horizontal
            data={data}
            keyExtractor={(item, idx) => String(item)}
            
            renderItem={({ item, index }) => {
              const selected = index === currentIndex;
              return (
                <TouchableWithoutFeedback onPress={() => onSelected(index)}>
                  <View
                    style={[
                      styles.itemStyleHorizontal,
                      selected && styles.itemSelectedStyleHorizontal
                    ]}
                  >
                    <Text
                      style={{
                        textAlign: "center",
                        color: selected ? "black" : "grey",
                        fontWeight: selected ? "bold" : "normal"
                      }}
                    >
                      {item + ""}
                    </Text>
                  </View>
                </TouchableWithoutFeedback>
              );
            }}
          />
        </View>
      </>
    );
  }

const CalculatorStack = createStackNavigator();

export default function CalculatorTab() {
  return (
    <CalculatorStack.Navigator>
      <CalculatorStack.Screen name="Calculator" component={CalculatorScreen} />
      <CalculatorStack.Screen name="DiscountDetails" component={DiscountDetailsScreen} />
    </CalculatorStack.Navigator>
  );
}

const styles = StyleSheet.create({
    container: {
      flex: 10,
      backgroundColor: '#fff',
      padding: 20,      
    },
    rowContainerCheckBox: {
      flexDirection: 'row',
      backgroundColor: '#ffe',
      alignItems: 'center',
      justifyContent: 'space-between',
    },
    rowContainer: {
      flexDirection: 'row',
      backgroundColor: '#ffe',
      height: 40,
      alignItems: 'center',
      justifyContent: 'space-between',
    },
    divider: {
      flexDirection: 'row',
      backgroundColor: '#fff',
      height: 20,
      alignItems: 'center',
      justifyContent: 'space-between',
      
    },
    title: {
      fontWeight: "bold",
      marginVertical: 4
    }, 
    wrapperHorizontal: {
      height: 54,
      color: "black",
      alignItems: 'center',
      justifyContent: 'space-between',
    },
    itemStyleHorizontal: {
      marginRight: 10,
      height: 50,
      padding: 8,
      borderWidth: 1,
      borderColor: "grey",
      borderRadius: 25,
      textAlign: "center",
      justifyContent: "center"
    },
    itemSelectedStyleHorizontal: {
      borderWidth: 2,
      borderColor: "#DAA520"
    },
    paragraph: {
      color: "black",
      textDecorationColor: "yellow",
      textShadowColor: "red",
      textShadowRadius: 1,
      margin: 24
    },
    textBoldLeft: {
      fontWeight: 'bold',
      textAlign: 'left',
      fontSize:16,
    },
    textBoldRight: {
      fontWeight: 'bold',
      textAlign: 'right',
    },
    textBasicLeft: {
      textAlign: 'left',
    },
    textBoldWidth: {
      width: 90,
      fontWeight: 'bold',
      textAlign: 'left',
      fontSize:16,
    },
    textBasicWdith: {
      width: 90,
      textAlign: 'left',
    },
  
});

 
코드라인이 길어져서, style 은 별도 file 로 분리할 예정입니다.

code 가 반복도 많고 지저분하긴 한데, 우선 동작 중심으로 코딩 후 refactoring 진행.

Output

 

 

 

 

반응형