TIL | 37 React props, state

ym j·2021년 5월 1일
0

React

목록 보기
3/9
post-thumbnail

⚛ React props, state

props란?

  • propertites이며, 단어의 뜻대로 해당 컴포넌트의 속성값이다. (html에서 사용했던 attribute과 비슷하지만, react의 경우 네이밍을 자유롭게 지정할 수 있다.)

  • 부모 컴포넌트로부터 전달받은 데이터를 props라는 객체 에 저장하게 된다.(key, value)

  • 자식 컴포넌트는 props를 통해 부모의 state에 저장된 데이터값과 eventhandler를 받을 수 있다.

  • state는 컴포넌트 자신이 갖고 있는 데이터 창고같은 느낌이라면, props는 데이터를 전달하는 통로라고 생각하면 편하다.


props 사용 예시

1. 부모 컴포넌트

import React from "react";
import Child from "./Child";
//
export default class Parents extends React.Component {
  render() {
    return (
      <>
        <Child data="hello world" />
      </>
    );
  }
}

2. 자식 컴포넌트

import React from "react";
//
export default class Child extends React.Component {
  render() {
    return (
      <>
        <div>{this.props.data}</div>
      </>
    );
  }
}
  • 부모 컴포넌트는 data라는 props를 통해서, 자식 컴포넌트에게 객체 형식 으로 데이터를 전달하게 된다.

  • 자식 컴포넌트는 props를 통해 받아온 정보를 사용할 수 있다.

  • props의 전달 방향은 항상 단방향(부모 컴포넌트 -> 자식 컴포넌트) 이며 형제 컴포넌트들간의 전달은 불가능하다.



state란?

  • 컴포넌트의 상태, 즉 컴포넌트 자신이 갖고 있는, 데이터 및 정보를 담은 객체이다. (props, state 모두 객체 형태로 데이터 저장)

  • 컴포넌트 내에서 정의하고 method를 통해 수정할 수 있으며, props를 통해서 자식 컴포넌트에게 해당 데이터를 전달할 수 있다.


state 사용 예시

1. 부모 컴포넌트

import React from "react";
import Child from "./Child";
//
export default class Parents extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: "red" };
  }
  render() {
    return (
      <>
        <Child textColor={this.state.color} content="안녕하세요" />
      </>
    );
  }
}

2. 자식 컴포넌트

import React from "react";
//
export default class Child extends React.Component {
  render() {
    return (
      <>
        <div style={{ color: this.props.textColor }}>{this.props.content}</div>
      </> // 예시를 위해 inline으로 스타일을 지정하였다.
    );
  }
}
  • 부모 컴포넌트는 state라는 객체 안에 color:red 라는 데이터를 저장했으며, textColor라는 props를 통해 자식 컴포넌트로 데이터를 전달하였다.

  • 자식 컴포넌트는 textColor 를 통해 부모 컴포넌트의 state에 접근하여 color를 빨간색으로 지정할 수 있었다.



Reference

profile
블로그를 이전하였습니다 => "https://jymini.tistory.com"

0개의 댓글