본문 바로가기
React/React Native

리액트 네이티브] 15. propTypes

by 김마리님 2023. 2. 1.

리액트 네이티브는 자바스크립트 기반이기 때문에 자료형 타입을 크게 나누지 않는 문제가 있다. 막상 빌드해놓고 보면 자료형 때문에 오류가 나는 경우도 있고..

그걸 방지하기 위해 propsType를 쓴다.

그럼 어떻게 쓰는가?

 

먼저 의존성을 부여한다.

npm install props-types

혹은

yarn add prop-types

 

자료형을 받는 간단한 케이스인 TextInput에 값을 넣는 예시로 알아보자.

 

루트 App.js

더보기
import App from "./src/App";

export default App;

 

- ../src/App.js

import React, { useState } from "react";
import { StatusBar } from "react-native";
import styled, { ThemeProvider } from "styled-components/native";
import { theme } from "./theme"
import Input from "./component/Input";

const Container = styled.SafeAreaView`
    flex: 1;
    background-color: ${({ theme }) => theme.background };
    align-items: center;
    justify-content: flex-start;
`;

export default function App() {

    const [newTask, setNewTask] = useState('');

    const addTask = () => {
        alert(`Add ${newTask}`);
        setNewTask('');
    };

    const handleTextChange = text => {
        setNewTask(text);
    }

    return (
        <ThemeProvider theme = {theme}>
            <Container>
				...
                <Input 
                    placeholder = "+ Add a Task"
                    value = {newTask}
                    onChangeText = {handleTextChange}
                    onSubmitEditing = {addTask}/>
            </Container>
        </ThemeProvider>
    );
}

 

- .. /component/Input.js

import React from "react";
import { Dimensions, useWindowDimensions } from "react-native";
import styled from "styled-components/native";
import PropTypes from "prop-types";

const StyledInput = styled.TextInput.attrs(({ theme }) => ({
	...
`;

const Input = ({ placeholder, value, onChangeText, onSubmitEditing }) => {
    //const width = Dimensions.get('window').width;
    const width = useWindowDimensions().width
    return <StyledInput 
                width = {width}
                placeholder = {placeholder}
		...
                value = {value}
                onChangeText = {onChangeText}
                onSubmitEditing = {onSubmitEditing}/>;
};

Input.propTypes = {
    placeholder : PropTypes.string,
    value : PropTypes.string.isRequired,
    onChangeText : PropTypes.func.isRequired,
    onSubmitEditing : PropTypes.func.isRequired,
};

export default Input;

 

Input을 호출할 때 4개의 Property를 요청하는 것이 보인다.

placeHolder은 문자열,

value도 문자열(newTask 값인데, useState에 기본 자료형이 문자열인것이 보인다.)

onChangeText와 onSubmitEditing은 const 함수를 프로퍼티로 넣는 것이 보인다. (onSubmit는 키보드의 retrun 값을 누르면 발생하는 이벤트이다.)

 

Input에 4개의 Property를 받아와서 TextInput의 속성에 받아온 프로퍼티를 넣는다.

이 때, 가져온 프로퍼티의 자료형을 확인하기 위해 아래의 코드에

Input.propTypes를 이용해 자료형을 확인할 수 있다.

isRequired를 넣으면 필수로 값을 넣어야 한다.

 

이 결과값은..

 

 

 

그럼 만약에 자료형이 다른 값을 넣는다면 어떻게 될까?

 

string으로 선언해둔 변수인데, 배열로 값을 넣으니까 오류가 뜨는 것을 볼 수 있다.

 

만약 자료형이 정해진 자료형이 아닌 enum 등으로 선언된 경우라면 어떻게 해야할까? 예시를 보자.

 

- ../src/images.js

...
export const images = {
    uncompleted : checkBoxOutline,
    complete : checkBox,
    delete : deleteForever,
    update : edit,
}
...

 

- ../src/component/IconButton.js

...
import PropsTypes from 'prop-types';
import { images } from "../image";

...
const IconButton = ({ type, onPressOut }) => {
    return (
        <TouchableOpacity onPressOut={onPressOut}>
            <Icon source={type} />
        </TouchableOpacity>
    );
}

IconButton.PropsTypes = {
    type: PropsTypes.oneOf(Object.values(images)).isRequired,
    onPressOut: PropsTypes.func,
}
...

 

image 파일 내부에 선언된 enum 타입의 변수가 보인다.

이의 타입을 사용하기 위해 

PropsTypes.oneOf(Object.values(변수))

라는 형태가 사용된 것을 볼 수 있다.

반응형