프로그래밍/리액트네이티브

react_native Modal / Pressable / RefreshControl

TONY07 2021. 6. 8. 13:12

개요

    - Modal : 특정 이벤트에서 새창을 띄었을때 원래 하던 작업을 계속 이어갈 수 있게 해놓은 것이 모달리스이다.

                 특정 이벤트에서 확인하거나 특정 이벤트를 날려주지 않으면 원래 하던 작업을 계속 이어갈수 없는
                 새창을 모달이라고 한다.  ex) 팝업창

    - Pressable : touchableopacity 와 같이 버튼의 역할을 하지만, 더 다양한 press 단계를 추적할 수 있다.

    - Refreshcontrol  :  ScrollView 또는 ListView 내에서 화면을 끌어내려서 새로 고침을 추가하는데 사용된다.

 

 

 

import React, { useState } from "react";
import { Alert, Modal, StyleSheet, Text, Pressable, View } from "react-native";

const App = () => {
  const [modalVisible, setModalVisible] = useState(false);
  return (
    <View style={styles.centeredView}>
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          Alert.alert("Modal has been closed.");
          setModalVisible(!modalVisible);
        }}
        onShow={() =>{
          Alert.alert("Modal has been open.");
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>Hello World!</Text>
            <Pressable
              style={[styles.button, styles.buttonClose]}
              onPress={() => setModalVisible(!modalVisible)}
            >
              <Text style={styles.textStyle}>Hide Modal</Text>
            </Pressable>
          </View>
        </View>
      </Modal>
      <Pressable
        style={[styles.button, styles.buttonOpen]}
        onPress={() => setModalVisible(true)}
      >
        <Text style={styles.textStyle}>Show Modal</Text>
      </Pressable>
    </View>
  );
};

const styles = StyleSheet.create({
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 22
  },
  modalView: {
    margin: 20,
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5
  },
  button: {
    borderRadius: 20,
    padding: 10,
    elevation: 2
  },
  buttonOpen: {
    backgroundColor: "#F194FF",
  },
  buttonClose: {
    backgroundColor: "#2196F3",
  },
  textStyle: {
    color: "white",
    fontWeight: "bold",
    textAlign: "center"
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center"
  }
});

export default App;

 

Modal

https://reactnative.dev/docs/modal

 

Modal · React Native

The Modal component is a basic way to present content above an enclosing view.

reactnative.dev

 - Props

    -  visible [자료형 : Boolean ]     :  true , false 로 설정하며 보이게 또는 안보이도록 설정하기 위해서 사용됨

    -  transparent   [자료형 : Boolean ]   :   true인경우 <Modal /> 의 뒷 배경이 없는 transparent 상태를 가지게됨.
       불투명 효과 적용시 배경값을 불투명하게 적용하여 사용한다.
       내부 콘텐츠의 크기를 작게할 경우 가려진 콘텐츠가 불투명하게 드러나게 됨
    -  animation [자료형 : ENUM ('none', 'slide', 'fade') ]     default : none
:   Modal을 보이거나 사라질 때 간단한 애니메이션을 적용한다.

none   :  애니메이션 효과 없이 적용됨
slide    : 하단에서부터 이동하는 효과
fade    : 서서히 나타나는 FadeInOut 효과 

 

     - onRequestClose  [ function ]   :   모달을 닫는 경우 실행될 콜백 함수를 등록한다.  

     - onShow  [ function ]  : 모달이 보이게되면 실행될 콜백함수를 등록함.

 

 

 

Pressable

https://reactnative.dev/docs/pressable

 

Pressable · React Native

Pressable is a Core Component wrapper that can detect various stages of press interactions on any of its defined children.

reactnative.dev

 

import React, { useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';

const App = () => {
  const [timesPressed, setTimesPressed] = useState(0);

  let textLog = '';
  if (timesPressed > 1) {
    textLog = timesPressed + 'x onPress';
  } else if (timesPressed > 0) {
    textLog = 'onPress';
  }

  return (
    <View style={styles.container}>
      <Pressable
        onPress={() => {
          setTimesPressed((current) => current + 1);
        }}
        style={({ pressed }) => [
          {
            backgroundColor: pressed
              ? 'rgb(210, 230, 255)'
              : 'white'
          },
          styles.wrapperCustom
        ]}>
        {({ pressed }) => (
          <Text style={styles.text}>
            {pressed ? 'Pressed!' : 'Press Me'}
          </Text>
        )}
      </Pressable>
      <View style={styles.logBox}>
        <Text testID="pressable_press_console">{textLog}</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
  },
  text: {
    fontSize: 16
  },
  wrapperCustom: {
    borderRadius: 8,
    padding: 6
  },
  logBox: {
    padding: 20,
    margin: 10,
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: '#f0f0f0',
    backgroundColor: '#f9f9f9'
  }
});

export default App;

 

 - Props

 

      -    onPress

               손가락으로 터치후에 때면 이벤트 발생

      -    onPressIn

               손가락으로 터치하면 이벤트 발생

      -    onPressout 

               손가락으로 터치 때면 이벤트 발생

      -    children

               아래코드는 pressed 는 pressable 를 통해 터치를 하고있는지 true false를 준다. 터치를 하고있으면
                Pressed! 터치를 하고 있지 않을시에는 Press Me 를 띄운다.

 {({ pressed }) => (

          <Text style={styles.text}>

            {pressed ? 'Pressed!' : 'Press Me'}

          </Text>

)}

           

 

 

RefreshControl 

      https://reactnative.dev/docs/refreshcontrol

 

RefreshControl · React Native

This component is used inside a ScrollView or ListView to add pull to refresh functionality. When the ScrollView is at scrollY: 0, swiping down triggers an onRefresh event.

reactnative.dev

 

 

 

 

   - Props

import React from 'react';
import { RefreshControl, SafeAreaView, ScrollView, StyleSheet, Text } from 'react-native';

const wait = (timeout) => {
  return new Promise(resolve => setTimeout(resolve, timeout));
}

const App = () => {
  const [refreshing, setRefreshing] = React.useState(false);

  const onRefresh = React.useCallback(() => {
    setRefreshing(true);
    wait(2000).then(() => setRefreshing(false));
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollView}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
          />
        }
      >
        <Text>Pull down to see RefreshControl indicator</Text>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
    backgroundColor: 'pink',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;

 

          - onRefresh

                  새로고침이 활성화 될때 실행된다.    ( type : function )

          - refreshing(필수)

                  새로 고침을 활성화 할지 표시한다.