Mobile 개발/RN Project - Realty Reg.

RN Prj - react navigation prop reference

히핑소 2020. 8. 12. 21:39
반응형

stacknavigation 으로 연결된 stack function 끼리 전환하는 case에서 인자에 props 전달하는 방법 입니다.

navigate() 호출 시 props 값에 넣어준 url 대로 webview screen을 띄우려고 search 하다가 삽질도 좀 하고 알게 되었네요

참고한 부분은 react-navigation 입니다

https://reactnavigation.org/docs/navigation-prop/

 

React Navigation

Each `screen` component in your app is provided with the `navigation` prop automatically. The prop contains various convenience functions that dispatch navigation actions on the route's router. It looks like this:

reactnavigation.org

React Navigation 에 있는 sample code 를 보면, Home Stack 에서 Profile Stack 으로 screen 전환을 합니다.

이 때, 인자로 props 를 넘겨줄 수 있는데, 다음 과드와 같이 ProfileScreen function component 인자에 route 선언하면,

homeScreen 의  navigate() 안에 선언된 names: ['Brent', 'Satya', 'Micha'] array 가 넘어갑니다.

그리고, route.params.names 로 naming 하면 값을 정상적으로 받아옵니다.

 

route 와 params 는 미리 정의된 react variable 로, 변경하면 안됩니다.

route 대신 맘대로 naming 했다가 괜히 시간만 낭비한..

import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

function HomeScreen({ navigation: { navigate } }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>This is the home screen of the app</Text>
      <Button
        onPress={() =>
          navigate('Profile', { names: ['Brent', 'Satya', 'Michaś'] })
        }
        title="Go to Brent's profile"
      />
    </View>
  );
}

function ProfileScreen({ navigation, route }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Profile Screen</Text>
      <Text>Friends: </Text>
      <Text>{route.params.names[0]}</Text>
      <Text>{route.params.names[1]}</Text>
      <Text>{route.params.names[2]}</Text>
      <Button title="Go back" onPress={() => navigation.goBack()} />
    </View>
  );
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Profile" component={ProfileScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

 

위 내용 적용한 Realty Project, CalculateTab.js 코드는 다음과 같습니다.

import React, {useState} from 'react';
import { Button, Text, View, TextInput, Alert, FlatList, TouchableWithoutFeedback} from 'react-native';
import { createStackNavigator } from '@react-navigation/stack';
import {WebView} from 'react-native-webview';

function SearchDetailScreen({route}) {
  return (
    <WebView
        source={{uri: route.params.url}}
        originWhitelist={['*']}
        javaScriptEnabled={true} // Used on Android only as JavaScript is enabled by default on iOS
        useWebKit={true} //ios webkit enable
    />
  );
}


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({
    taxRate:0, taxPrice:0, localRate:0, localPrice:0, specialRate:0, specialPrice:0,
    });
  const [totalValue, setTotalPrice] = useState(0);

  const calculateHandler = (officialPrice, realPrice, tax) => {
    if (buyingValue > 0 && officialValue > 0) {
      setBondPrice(officialPrice);
      setIncomePrice(realPrice);
      setHomeTax({
        taxRate:tax.taxRate, taxPrice:tax.taxPrice,
        localRate:tax.localRate, localPrice:tax.localPrice, 
        specialRate:tax.specialRate, specialPrice:tax.specialPrice,
      });
      setTotalPrice(officialPrice + realPrice + tax.taxPrice + tax.localPrice + tax.specialPrice + 
        calculateRegistrationFee(fontStyleIdx));
    } else {
      Alert.alert(
        '입력 오류',
        '거래금액, 공시지가 모두 입력',
        [{ text: 'Cancel'},{ text: 'OK'}], { cancelable: false }
      )
    }
  }

  const calculateRegistrationFee = (fontStyleIdx) => {
    return fontStyleIdx == 0 ? 15000 :
      fontStyleIdx == 1 ? 13000 : 11000;
  }

  return (
    <View style={GlobalStyles.calculatorContainer}>
      <View style={GlobalStyles.calculatorRowContainerCheckBox}>
        <Text style={GlobalStyles.calculatorTextBoldLeft}>등기 수수료 납부</Text>          
        <CustomPicker
          data={fontStyles}
          currentIndex={fontStyleIdx}
          onSelected={setFontStyleIdx}
        />
      </View>

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

      <View style={GlobalStyles.calculatorRowContainer}>
        <Text style={GlobalStyles.calculatorTextBoldLeft}>공시지가 입력</Text>
        <TextInput
          placeholder='0'
          keyboardType={'number-pad'}
          returnKeyType='done'
          style={{width:100,  padding:5, textAlign:'right'}}
          onChangeText={text => onChangeOfficialValue(text)}
          value={officialValue}
        />
        <Text style={GlobalStyles.calculatorTextBasicRight}>만원</Text>
        <LaunchCalculate officialValue={officialValue * 10000} buyingValue={buyingValue * 10000} 
          sellRate={sellRate} residenceOfCity={residenceOfCity} category={category} 
          calculateHandler={calculateHandler}/>
      </View>

      <View style={GlobalStyles.calculatorRowContainer}>
        <Text style={GlobalStyles.calculatorTextBoldLeft}>공시지가 확인</Text>
        <Button
          title="국토교통부 가격열람"
          onPress={() => navigation.navigate('SearchDetail', {url:'https://www.realtyprice.kr:447/notice/town/nfSiteLink.htm'})}
        />
      </View>

      <View style={GlobalStyles.calculatorRowContainer}>
        <Text style={GlobalStyles.calculatorTextBoldLeft}>채권매도할인율 입력</Text>
        <TextInput
          placeholder = {BOND_RATE.toString()}
          keyboardType={'numeric'}
          returnKeyType='done'
          style={{padding:5, textAlign:'right'}}
          onChangeText={text => onChangeSellRate(text)}
          value={sellRate}
        />
        <Button
          title="할인률 조회"
          onPress={() => navigation.navigate('SearchDetail', {url:'https://svc.wooribank.com/svc/Dream?withyou=HBNHB0036'})}
        />
      </View>
    </View>
  );
}
const CalculatorStack = createStackNavigator();

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

 

적용 시 '국토교통부 가격열람' URL 과 '채권매도할인율 조회' URL 을 webview 로 띄울 수 있습니다.

셀프등기가이드 앱 화면

 

반응형