Language/React.js

[React] React State

마탁이 2021. 1. 24. 18:29

1. React State

 - React 구성 요소에는 기본으로 제공되는 state 개체가 있다.

 - state 객체는 컴포넌트에 속하는 속성 값을 저장하는 곳.

 - state 객체가 변경될 때, 컴포넌트는 리-렌더링 한다.

 - 아래와 같이 state 객체를 사용할 수 있다.

import React from 'react';
import ReactDOM from 'react-dom';

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

ReactDOM.render(<Car />, document.getElementById('root'));

 - 또한 아래와 같이 setState() 함수를 이용해 state 객체의 값을 변경할 수 있다.

   setState()를 사용하면 컴포넌트가 업데이트되었음을 인식하고 render() 함수 및 기타 모든 수명주기 관련 함수를 호출한다.

import React from 'react';
import ReactDOM from 'react-dom';

class Car extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            brand: "Ford",
            model: "Mustang",
            color: "red",
            year: 1994,
        };
    }

    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>
        );
    }
}

ReactDOM.render(<Car />, document.getElementById('root'));

'Language > React.js' 카테고리의 다른 글

[React] React Event  (0) 2021.01.24
[React] React 수명주기(Lifecycle)  (0) 2021.01.24
[React] 컴포넌트 Prop  (0) 2021.01.24
[React] React 컴포넌트  (0) 2021.01.24
[React] React JSX  (0) 2021.01.23