클래스형 컴포넌트
작성 수정
17.x.x버전부터import React from "react"를 생략할 수 있다.
1. 컴포넌트 생성
Component클래스를 상속해서 만든다.Component클래스는render,constructor등의 메서드를 갖고있다.
import { Component } from 'react';
class App extends Component {
constructor(){
...
}
render() {
return (
<div className='App'></div>
)
}
}
1. render()
render()함수는return을 통해DOM을 랜더링한다.
2. constructor()
state를 초기화를 하는 곳이자,state를 직접 할당할 수 있는 유일한 곳이다.- 그 외에
state를 수정하려면this.setState()를 사용해야 한다. - 인스턴스에 이벤트 처리 메서드를 바인딩을 하는 곳이다.
constructor(props) {
super(props);
this.state = { counter: 0 }; // state 초기화
this.handleClick = this.handleClick.bind(this); // 이벤트 처리 메서드 바인딩
}
this는 해당 컴포넌트를 가리킨다.
3. this 객체 파헤치기
for(let property in this){
console.log(property)
}
this의 프로퍼티들
propsstatesetStateforceUpdatecontextrefsupdater_reactInternals_reactInternalInstanceisReactComponent
2. 이벤트 핸들러
1) 이벤트 핸들러의 this
<button onClick ={function(){console.log(this)}} />
// ❌
- 일반 함수로 작성하면
this는undefined를 가리킨다.
<button onClick ={function(){console.log(this)}.bind(this)} />
bind(this)를 통해this가 해당 컴포넌트를 바라보게 한다.
<button onClick ={()=>console.log(this)} />
- 화살표 함수의
this는 상위 스코프를 바라보기 때문에 이를 이용할 수 있다.
2. state 변경
this.state = {name:"Unknown", job:"developer"}
// ❌
this.setState({name:"junha", age:"20"})
// ✅
setState() 차이
- 함수형 컴포넌트:
state교체 - 클래스형 컴포넌트:
Object.assign(newObj,prevObj)방식으로 병합var _assign = require('object-assign'); ... return _assign({}, prevState, partialState);
3. 클래스형 컴포넌트 예시
import { Component } from 'react';
class App extends Component {
state = { age: 17 };
modify = () => {
const { age } = this.state;
this.setState({ age: age + 1 });
};
componentDidMount() {
this.modify();
}
render() {
const { age } = this.state;
return (
<>
<h1>{age}</h1>
<button onClick={this.modify}>+age</button>
</>
);
}
}