TIL # 40 (State & Event)

Mikyung Lee·2021년 1월 29일
1
post-thumbnail

1. State

  • State : 상태
  • 컴포넌트 내부에서 가지고 있는 컴포넌트의 상태값, 화면에 보여줄 컴포넌트 UI 정보(상태)를 지니고 있는 객체
  • 컴포넌트 내에서 정의하고, 사용하며 데이터(객체)가 변경될 수 있다.

Class component | state

크게 import, class, export3가지로 나눠지고, state를 적용해 주려면 render함수 위에 constructor함수를 작성하고, super()을 호출하고, this.state를 불러야 한다.

import React from 'react';

class State extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }
  
  render() {
    return (
      <div>
        <h1>Class Component | State</h1>
        </div>
      );
  }
}

export default State;

state 에서 상태값을 설정하는 이유는 결국 컴포넌트 안의 요소에서 그 상태값을 반영해서 데이터가 바뀔 때마다 효율적으로 화면(UI)에 나타내기 위해서다.

<h1 style = {{ color: this.state.colr }}>Class Component | State</h1>
import React, { Component } from 'react';

export 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
front-end developer 🌷

0개의 댓글