FrontEnd/React
클래스형 컴포넌트 vs 함수형 컴포넌트
Bumang
2023. 10. 5. 09:34
클래스형 컴포넌트
import { Component } from 'react';
export default class MyComponent extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
count: 0,
};
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
const { count } = this.state;
return (
<div>
<div>{count}</div>
<button onClick={this.handleClick}>클릭해보세요!</button>
</div>
);
}
}
- react 라이브러리에서 제공하는 Component를 import 받아와서 상속 관계를 맺어주었음.
- 따라서, react에서 만든 Component라는 class의 프로터피와 메서드를 사용할 수 있다.
- super는 class의 constructor에서 부모의 constructor 메서드를 실행시킨다.
- 만약 생략하면 constructor() {} 가 자동으로 생성되며, 자식 클래스에서 생략하면 constructor(...args) { super(...args) } 가 암묵적으로 생성되기 때문에 생략도 가능하다.
- 자식 클래스에서는, constructor에 인스턴스 프로퍼티를 사용하기 위해서 this를 사용해야 하는데, this를 사용하기 전 항상 super 키워드를 붙여 주도록 되어있다. ECMAScript에서 고정시켜두었음.
- 여기서 super(props) 를 넘기는데 이는 React.Component에 그렇게 하도록 되어있기 때문이다.
- render 메서드 선언
- class 컴포넌트는 반드시 render 메서드가 존재해야 하고, 렌더링 하고 싶은 jsx를 return 하면 된다.
- return 문 안에는 button에 onClick이 있고, 클릭 시 실행되는 handleClick이 () 실행문이 붙지 않은 상태로 함수 자체를 넘겨주고 있다.
함수형 컴포넌트
import { useState } from 'react';
export default function MyComponent(props) {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<div>{count}</div>
<button onClick={handleClick}>클릭해보세요!</button>
</div>
);
}
- return 문 안에는 jsx가 사용되었다.
- onClick에는 여전히 () 실행하는 것이 아닌 선언되어 있는 함수 자체가 반환되었다. react 내부적으로 어디에선가 실행될 것이다.
- 함수 내부에 값으로 선언된 함수이기 때문에 this를 붙여서 넘겨줄 필요가 없다.