React Native Tutorial 따라하기 – Props

props 이라는 것을 사용하여 Component를 원하는 형태로 생성하는 것이 가능하다. 예를 들면 Image라는 Component에 source props를 설정하여 원하는 이미지를 표현하는 Component로 만드는 것이 가능하다. 다음은 그에 대한 예제이다.

import React, { Component } from 'react';
import { AppRegistry, Image } from 'react-native';

export default class Bananas extends Component {
  render() {
    let pic = {
      uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
    };
    return (
      <Image source={pic} style={{width: 12, height: 110}}/>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => Bananas);

props를 직접 정의하는 것도 가능하다. 임의의 Component를 만들 때 this.props를 사용해서 새로운 props를 정의할 수 있다. 다음 예제를 보자.

import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';

class Greeting extends Component {
  render() {
    return (
      <View style={{alignItems: 'center'}}>
        <Text>Hello {this.props.name}!</Text>
      </View>
    );
  }
}

export default class LotsOfGreetings extends Component {
  render() {
    return (
      <View style={{alignItems: 'center', top: 50}}>
        <Greeting name='Rexxar' />
        <Greeting name='Jaina' />
        <Greeting name='Valeera' />
      </View>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => LotsOfGreetings);

코드를 보면 Greeting 이라는 Compnent를 생성했고 해당 Component는 Text를 출력하는 Component다. 이때 props.name 이라는 값을 사용해서 ‘Hello [무엇]’을 출력할 수 있도록 한다.

This Post Has One Comment

Leave a Reply