React-State

김진우·2023년 7월 19일
0

react

목록 보기
3/4

State

  • 스테이트란 컴포넌트에서 간단하게 무언가를 "기억하기" 위해 사용
  • state사용 시 constructor 안에서 생성 해 줘야함

1. State 생성하기

아래와 같이 constructor를 사용하고, this.state로 null을 만들어준다.

constructor(props) {
  super(props);
  this.state = {
    value: null,
  }
}

2. State 으로 변경하기

아래와 같이, square를 눌렀을때 setState를 이용하여, 'X'라는 값 넣어주기(null -> 'X'로)

<button className="square" onClick={() => { this.setState({value: 'X'})}}>

3. State 이용하기

아래와 같이 this.state.value - this에 state를 붙이고 사용하기

render() {
  return(
    <button className="square" onClick={() => { 
    	this.setState({value: 'X'})}}>
 	   {this.state.value}
	</button>
		)
    }
profile
Code log

1개의 댓글

comment-user-thumbnail
2023년 7월 19일

이 글은 저에게 많은 도움이 되었습니다.

답글 달기

관련 채용 정보