패스트캠프 프론트앤드 인강 32일차 리액트에서 클래스형 컴포넌트의 state와 props를 배워보았다.
class형 컴포넌트는 컴포넌트를 형성하는 또다른방법이다. 요즘잘 사용하지않지만 유지보수나 특정 훅을 다루기위해 알아둘필요는있다.
먼저 함수형컴포넌트에서는
import React from "react";
export default function Hello({ color, isSpecial, name }) {
return (
<div style={{ color }}>
{isSpecial && <b>*</b>}
안녕하세요 {name}
</div>
);
}
Hello.defaultProps = {
name: "이름없음"
};
class형 컴포넌트에서는 이렇게 표현한다.참고로 defaultProps는 함수형컴포넌트에서사용한방법도 있고 아래처럼 static을 사용한방법이있다.
import React, { Component } from "react";
class Hello extends Component {
static defaultProps = {
name:'이름없음',
}
render() {
const { color, isSpecial, name } = this.props;
return (
<div style={{ color }}>
{isSpecial && <b>*</b>}
안녕하세요 {name}
</div>
);
}
}
export default Hello;
import React from "react";
import ReactDOM from "react-dom";
import Hello from "./Hello";
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<Hello />
</React.StrictMode>,
rootElement
);
클래스형 컴포넌트로 counter를 만들어보자.
import React, { Component } from "react";
class Counter extends Component {
handleIncrease() {
console.log("increase");
}
handleDecrease() {
console.log("decrease");
}
render() {
return (
<div>
<h1>0</h1>
<button onClick={this.handleIncrease}>+1</button>
<button onClick={this.handleDecrease}>-1</button>
</div>
);
}
}
export default Counter;
import React, { Component } from "react";
class Counter extends Component {
constructor(props) {
super(props);
this.handleIncrease = this.handleIncrease.bind(this);
this.handleDecrease = this.handleDecrease.bind(this);
// 초기값 무조건 객체
this.state = {
counter: 0
};
}
handleIncrease() {
this.setState({
counter: this.state.counter + 1
});
}
handleDecrease() {
// console.log("decrease");
this.setState({
counter: this.state.counter - 1
});
}
render() {
return (
<div>
<h1>{this.state.counter}</h1>
<button onClick={this.handleIncrease}>+1</button>
<button onClick={this.handleDecrease}>-1</button>
</div>
);
}
}
export default Counter;
constructor 바인드 하는 이유.
this.setState를 사용해야하는데 이미 함수를 버튼 onclick에 연결해주었는데 함수안에 또다른 this를 사용하는 순간 자신을 가르기기때문에, 기본 함수와 this와의 연결이 사라져버린다.
bind 대신에 화살표함수를 쓰는 방법도 있다.
// this.handleIncrease = this.handleIncrease.bind(this);
// this.handleDecrease = this.handleDecrease.bind(this);
...
}
handleIncrease = () => {
this.setState({
counter: this.state.counter + 1
});
};
handleDecrease = () => {
// console.log("decrease");
this.setState({
counter: this.state.counter - 1
});
};
그리고 초기값이 여러개일 경우에 한개의 초기값을 수정하고싶은경우 수정할애만쓰면 다 써주지않아도 자동업데이트되지만
초기값안에 객체가 있을경우엔 불변성유지를 위해 다 써줘야한다.
...this.state.updateMe, 처럼 모든애들을 불러오면된다.
import React, { Component } from "react";
class Counter extends Component {
state = {
counter: 0,
fixed: 1,
updateMe: {
toggleMe: false,
dontChangeMe: 1
}
};
...
handleTest = () => {
this.setState({
updateMe: {
...this.state.updateMe,
toggleMe: !this.state.updateMe.toggleMe
}
});
};
...
프론트엔드 개발 올인원 패키지 with React Online. | 패스트캠퍼스
성인 교육 서비스 기업, 패스트캠퍼스는 개인과 조직의 실질적인 '업(業)'의 성장을 돕고자 모든 종류의 교육 콘텐츠 서비스를 제공하는 대한민국 No. 1 교육 서비스 회사입니다.
www.fastcampus.co.kr
'Frontend' 카테고리의 다른 글
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지 34회차 미션 (0) | 2020.09.12 |
---|---|
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지 33회차 미션 (0) | 2020.09.11 |
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지 31회차 미션 (0) | 2020.09.09 |
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지 30회차 미션 (0) | 2020.09.08 |
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지 29회차 미션 (0) | 2020.09.07 |