[TIL]state

YUJIN'S CODE·2021년 10월 31일
0

React

목록 보기
2/2
post-thumbnail

🔍 state

state란 컴포넌트 내부에서 바뀔 수 있는 값을 의미한다.
클래스형 컴포넌트, 함수형 컴포넌트에서 통해 사용하는 state 두 가지 종류가 있다.

💻 state를 사용해보자!


import React from 'react';

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

  render() {
    return (
      <div>
        <h1>Class Component | State</h1>
      </div>
    );
  }
}

export default State;

💻

import React, { Component } from 'react';

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

  handleColor = () => {
    this.setState({
      color: 'blue'
    })
  }

  render() {
    return (
      <div>
        <h1 style={{ color: this.state.color }}>Class Component | State</h1>
        <button onClick={this.handleColor}>Click</button>
      </div>
    );
  }
}

export default State;
profile
I Love Pizza, 나만의 토핑으로 한조각씩 맞춰가는 중

0개의 댓글