Props

Gunwoo Kim·2021년 5월 30일
0
post-thumbnail

Props

  • props : properties(속성)
  • 컴포넌트의 속성값
  • props는 부모 컴포넌트로부터 전달 받은 데이터를 지니고 있는 객체
  • props를 통해 부모 컴포넌트로부터 자식 컴포넌트에게 state의 상태값 event handler를 넘겨줄 수 있습니다.

class Component Props

부모 컴포넌트

// Parent.js

import React from 'react';
import Child from '../pages/Child/Child';

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }

  render() {
    return (
      <div>
        <h1>Parent Component</h1>
	<Child titleColor={this.state.color} />
      </div>
    );
  }
}

export default State;

부모 컴포넌트에서 import를 통해 자식 컴포넌트를 불러오며 불러온 자식 컴포넌트에 넘겨주고 싶은 state 또는 method를 넘겨줄 수 있습니다.

  • <Child titleColor={this.state.color} /> 에서 titleColor 가 자식 컴포넌트로 넘겨주는 값

자식 컴포넌트

// Child.js

import React from 'react';

class Child extends React.Component {
  render() {
    return (
      <div>
        <h1 style={{color : this.props.titleColor}}>Child Component</h1>
      </div>
    );
  }
}

export default State;

자식 컴포넌트에서는 this.props를 통해 부모 컴포넌트에서 넘겨준 값을 받아올 수 있습니다.

  • <h1 style={{color : this.props.titleColor}}>Child Component</h1> 에서 부모 컴포넌트에서 보내준 titleColor를 this.props.titleColor 로 값을 받아온다.

props는 읽기 전용입니다.

부모 컴포넌트에서 넘겨준 값은 this.props를 통해 가져올 수 있지만
props의 값을 변경 할 수는 없습니다.

리액트에서 props는 읽기만 가능하며 순수 함수 형태로 동작해야 합니다.

순수 함수

아래의 sum 함수를 보면 입력값을 바꾸려 하지 않고 항상 동일한 입력값에 대해 동일한 결과를 반환하는 함수를 순수 함수라고 합니다.

또 다른 함수 withdraw 의 경우 자신의 입력한 값을 변경하기 때문에 순수 함수가 아닙니다.

function sum(a, b) {
  return a + b;
}

function withdraw(account, amount) {
  account.total -= amount;
}

0개의 댓글