React Native

Props (React native)

SallyJ 2022. 9. 30. 19:18

Props는 부모Class가 가지고 있는 데이터를 자식Class에게 전달해주기 위한 수단으로,

부모의 데이터를 받은 자식Class의 Component 내에서 수정/변경이 불가하고 그대로 쓰이게되는 읽기전용 프로퍼티다.

 

사용법은 간단하다.

먼저 부모 Class에서는 자식Class를 import 해주고, render() 안에서 부모 Class의 어떤 데이터를 넘겨줄것인지만 적으면 된다.

// 부모 클래스
import React, { Component } from 'react';
import {View, Text, StyleSheet} from 'react-native';
import PropsChild from './propsChild';

class App extends Component {
  state = {
    sampleText: 'Hello world',
    sampleBoolean: false,
    sampleNum: 1
  }
  
  changeState = () => {
    if(this.state.sampleBoolean == false) {
      this.setState({
        sampleText: 'Text Changed!!!',
        sampleBoolean: true
      })
    } else {
      this.setState({
        sampleText: 'Hello world~!!',
        sampleBoolean: false
      })
    }
  }
  
  render() {
    return (
      <View>
        <PropsChild sampleText = {this.state.sampleText} changeState={this.changeState}/>
      </View>
    )
  }
}
export default App;
// 자식 클래스
 import React from 'react';
 import {View, Text} from 'react-native';
 
 const PropsChild = (props) => {
    return (
        <View>
            <Text onPress={props.changeState}>
                {props.sampleText}
            </Text>
        </View>
    )
 }
 
 export default PropsChild;
댓글수0