롸?

Component, props, state 본문

WEB/React

Component, props, state

허니버터새우깡 2021. 12. 2. 16:20

1. 리액트란

React 또는 React.js는 자바스크립트 라이브러리의 하나로써 사용자 인터페이스를 만들기 위해 사용된다. JSX 문법과 ‘컴포넌트’라는 개념을 사용한다.

 

2. Component & Props

컴포넌트는 개념적으로 자바스크립트 함수와 유사하다. ‘props’라고 하는 임의의 입력을 받은 후, 화면에 어떻게 표시되는지를 기술하는 React 엘리먼트(HTML 태그)를 반환한다.
welcome 컴포넌트의 props인 name은 상위 컴포넌트인 App컴포넌트에서 Html 태그와 Html 태그의 attribute 같이 지정하고, welcome에게 상속된다.
props는 읽기 전용으로 상속받은 컴포넌트 내부에서 이를 수정해서는 안된다.

 

ES6 class 기반으로 간단한 welcome 컴포넌트 만들기
import React, { Component } from 'react';
 
class Welcome extends Component {
  render() {
    return (
      <div>
        <h1>Welcome {this.props.name}</h1>
        <p>This is simple Welcome Component</p>
      </div>
    );
  }
}
 
class App extends Component {
 
  render() {
    return (
      <div className="App">
        <Welcome name="Tom"></Welcome>
      </div>
    );
  }
}
 
export default App;
결과

 

3. State

state는 컴포넌트 내부에서 선언하며 내부에서 값을 변경할 수 있는 값이다. 하지만 state 값을 한 번 정의한 이후, 직접 수정해서는 안된다. this.state.comment = 'Hello'; 같은 방식으로 직접 수정할 경우, 다시 렌더링이 되지 않기 때문이다.
때문에 state 값을 변경하기 위해서는 setState()를 사용한다.

 


리액트에서는 데이터가 부모에서 자식으로 전달되기 때문에 부모 컴포넌트에서는 일반적인 방법으로는 자식 컴포넌트의 state 값을 알 수 없기 때문에 캡슐화가 가능하다.

 

State 선언하고 수정하기
class Contents extends Component {
  constructor(props){
    super(props);
    this.state = {
      title:'This is Title.',
      content:'Hello World!',
    }
  }
 
  render() {
    return (
      <div>
        <h3>{this.state.title}</h3>
        <p>
          {this.state.content}
        </p>
        <input type="button" value="Change"
          onClick={
            function(e) {
              e.preventDefault();
              this.setState({
                  title: "Changed Title"
              });
            }.bind(this)
          }
        ></input>
      </div>
    );
  }
}
결과

버튼 클릭 전
버튼 클릭 후

 

 


참고 

1.  https://ko.reactjs.org/docs/rendering-elements.html

2.  https://studyingych.tistory.com/52

3.  https://gseok.gitbooks.io/react/content/bd80-bd84-bd80-bd84-c9c0-c2dd-b4e4/react-propsc640-state-ac1c-b150-c815-b9ac.html

4.  생활코딩 리액트

Comments