So tired

React 개념 잡기 #3 (props와 state에 대해서) 본문

Programming/React

React 개념 잡기 #3 (props와 state에 대해서)

기짜낭 2020. 5. 2. 04:31
728x90

props

React의 props는 HTML의 attribute와 유사합니다.

예를 들어, "brand" attribute를 "Car" element에 추가해봅시다.

const myelement = <Car brand="Ford" />;

그럼 컴포넌트는 argument를 props object 처럼 받습니다.

아래 코드는 컴포넌트에서 "brand" attribute를 사용하는 모습입니다.

부모 컴포넌트로 부터 전달 받은 props는 하위 컴포넌트에서 this.props 라는 구문으로 사용가능합니다.

class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.brand}!</h1>;
  }
}

컴포넌트가 일반적인 자바스크립트의 함수라면, props는 함수의 입력값(input)이 됩니다.


props는 읽기 전용(read-only, immutable)입니다. 그래서 값을 변경하려고 하면 오류가 발생합니다.

이는 React가 단방향 데이터 흐름(One-way data flow)이기 때문입니다.

 

단방향 데이터 흐름(One-way data flow)이란?

React는 props를 전달할 때, 부모 컴포넌트에서 자식 컴포넌트 에게로만 데이터 전달이 가능합니다.

props의 흐름을 단방향으로 제한함으로써 데이터를 추적하기 쉽고 디버깅을 쉽게 해줍니다.

 

 

props를 Data라고 생각해도 무방합니다.
props는 불변, state는 가변, event는 flow-up, data는 flow-down


state

React 컴포넌트는 내장 (built-in) 되어 있는 상태 객체 (state 객체)를 지닙니다.

상태 객체는 컴포넌트에 속하는 property 값들을 저장하는 곳이다.

상태 객체가 변하면, 컴포넌트는 re-render 됩니다.


상태 객체는 constructor 내부에 다음과 같이 명시되어 초기화 됩니다.

상태 객체는 원하는 만큼 property를 포함할 수 있습니다.

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

어디서나 컴포넌트 내부의 상태 객체를 조회하기 위해서는 다음 문법을 사용하면 됩니다.

this.state.propertyname

상태 객체 내부의 값을 변경하기 위해서는 다음 메서드를 사용하면 됩니다.

this.setState()

setState로 인해 상태 객체 내부의 값이 변하게 되면, 컴포넌트는 re-render됩니다.

setState는 비동기 형태로 값이 업데이트 됩니다.

즉, 출력값이 새 값으로 전환됩니다.

 

다음은 setState를 이용한 예제입니다.

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  changeColor = () => {
    this.setState({color: "blue"});
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
        <button
          type="button"
          onClick={this.changeColor}
        >Change color</button>
      </div>
    );
  }
}

참고하면 좋은 글

 

React에서 Stateful 대 Stateless 함수형 컴포넌트

React는 인터랙티브한 UI를 구축하는 대중화된 자바스크립트 프론트 엔드 라이브러리 입니다. React는 상대적으로 빨리 배울 수 있는데, 그 점이 최근들어 주목을 끌게 된 이유 중 하나입니다. 훑어봐야 하는 중요한 개념들이 많겠지만, component는 React에서 가장 중요한 개념임이 명백합니다. React 개발자로서 component를...

code.tutsplus.com

 

 

React Props

React Props Props are arguments passed into React components. Props are passed to components via HTML attributes. React Props React Props are like function arguments in JavaScript and attributes in HTML. To send props into a component, use the same syntax

www.w3schools.com

 

Comments