티스토리 뷰

 타입스크립트의 기본적인 문법을 다뤄봤으니, 이제 이 타입스크립트를 리액트/리액트 네이티브에서 어떻게 사용을 하는 지 확인해보자.

 

Props를 어떻게 사용하여 자식 컴포넌트에 데이터를 전달하는게 JS 환경과 어떤 차이가 있는 지, 기본적인 예제 코드를 한 번 보자.

 

Json 형식을 사용할 수도 있지만, 타입 검사를 위해 interface를 사용한다.


◎ Profile.tsx

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

interface Props {
  name: string; // normal param
  isActive?: boolean; // optional param
  image?: string; // default param
  children: React.ReactNode; // children param
}

const Profile = ({
  name,
  isActive,
  image = 'https://picsum.photos/200',
  children,
}: Props) => {
  return (
    <View style={isActive && styles.activeStyle}>
      <Image source={{uri: image}} />
      <Text>{name}</Text>
      <Text>{children}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  activeStyle: {
    backgroundColor: 'yellow',
  },
});

export default Profile;

 

◎ App.tsx

import React from 'react';
import Profile from './Profile.tsx';
import {Text} from 'react-native';

const App = () => {
  return (
    <Profile name={'John Doe'}>
      <Text>Hello World</Text>
    </Profile>
  );
};

export default App;

 

Comments