본문 바로가기

Study/React

[React Native] 컴포넌트 다루기, 클래스형 컴포넌트와 함수형 컴포넌트

1. 컴포넌트에 자바스크립트 변수 값 넣기 : {} 사용

import React from "react";
import { SafeAreaView, Text } from "react-native";


export default function App() {

  const str = "Hello World";

  return (
    <SafeAreaView>
      <Text>Hello TSX World!</Text>
      <Text>{str}</Text>
    </SafeAreaView>
  );
}

 

2. 자바스크립트의 boolean 값에 따라 리턴할 컴포넌트 지정하기

import React from "react";
import { SafeAreaView, Text } from "react-native";

export default function App() {

  const isLoading:boolean = true

  if(isLoading) {
    return(
      <SafeAreaView>  
        <Text>Loading...</Text>
      </SafeAreaView>
    )
  } else {
    return (
      <SafeAreaView>
        <Text>Hello TSX World!</Text>
      </SafeAreaView>
    )
  }

}

 

3. boolean 값에 따라 보여줄 컴포넌트 지정

import React from "react";
import { SafeAreaView, Text } from "react-native";

export default function App() {

  const isLoading:boolean = true
  
  return (
    <SafeAreaView>
      {isLoading && <Text>Loading...</Text>}
      {!isLoading && <Text>Hello TSX</Text>}
      {isLoading ? <Text>Loading...</Text> : <Text>Hello TSX</Text>}
    </SafeAreaView>
  )
}

 

4. boolean 값에 따라 보여줄 컴포넌트 지정

import React from "react";
import { SafeAreaView, Text } from "react-native";

export default function App() {

  const isLoading:boolean = true

  const child:any = isLoading ? (<Text>Loading...</Text>) : (<Text>Hello TSX</Text>);
  return <SafeAreaView>{child}</SafeAreaView>;

}

 

5. map 함수를 사용하여 컴포넌트를 반복하여 넣어주기

import React from "react";
import { SafeAreaView, Text } from "react-native";

export default function App() {

  const isLoading:boolean = true

  const child = [ 1, 2, 3 ].map(i => <Text>Hello TSX World ... {i}</Text>)

  return <SafeAreaView>{ child }</SafeAreaView>

}

 

6. 클래스형 컴포넌트 vs. 함수형 컴포넌트

6-1. 클래스형 컴포넌트 : 함수형 컴포넌트가 등장하기 전까지 사용되던 컴포넌트 형태. 멤버변수, 생성자, 렌더함수가 존재함.

import React from "react";
import { SafeAreaView, Text } from "react-native";

export default class App extends React.Component {
  
  name:String = '';

  constructor(props:any) {
    super(props)
    this.name = "홍길동";    
  }

  render() {
      
    return(
      <SafeAreaView>
        <Text>Hello TSX {this.name}</Text>
      </SafeAreaView>
    )

  }

}

 

6-2. 함수형 컴포넌트

import React from "react";
import { SafeAreaView, Text } from "react-native";

export default function App() {
  
  let name:String = "홍길동";

  return (
    <SafeAreaView>
      <Text>Hello TSX {name}</Text>
    </SafeAreaView>
  )

}