TIL(2020.12.14)

김지민·2020년 12월 16일
0

TIL

목록 보기
7/28

0. Props

  • state에 대해 공부하기 전 Props에 대해 리와인드
  • 부모가 자식에게 값을 내려줄 때 사용
// 구문
<child value = 'value' />
  • 사실상 Props는 자식입장에서 볼 때 읽기 전용임.

1. state

  • state는 콤포넌트가 내부에서 갖고 있음
  • props와 달리 변경이 필요할때 사용
  • state는 setState()함수 사용해서 변경 가능

1-1. state 코드보기

App.js

import React, { Component } from 'react';
import Counter from './Counter'; // Counter.js 불러오기(state내장하고 있는 콤포넌트)

class App extends Component {
  render() {
    return <counter/ >;
    }
  }

export default App;

Counter.js state사용된 콤포넌트

import React, { Component } from 'react';

class Counter extends Component {
  state = {
    number : 0 // 기본 state 지정. 변화시킬 값(여기서는 number)에 대해 지정
  };
  
constructor(props) {
  super(props);
  this.handleIncrease = this.handleIncrease.bind(this);
  this.handleDecrease = this.handleDecrease.bind(this);
  }

handleIncrease = () => {
  this.setState({
    number : this.state.number + 1
  });
};
handleDecrease = () => {
  this.setState({
    number : this.state.number - 1
  });
};

  render() {
    return (
    <div>
    <h1>카운터</h1>
    <div> 값 : {this.state.number}</div>
    <button onClick = {this.handleIncrease}> + </button>
    <button onClick = {this.handleDecrease}> - </button>
    </div>
    );
  }
}
export default Counter;
profile
wishing is not enough, we must do.

0개의 댓글