2023.04.08 - [Front end/React] - 클래스 컴포넌트의 형태와 리액트 데브툴즈
클래스 컴포넌트의 형태와 비교해보세요.
클래스 컴포넌트의 형태와 리액트 데브툴즈
클래스 컴포넌트 설명 render의 return 부분 화면을 그리는 부분이다. 실제로 보면 Like 버튼아니면 'You liked this.'라는 텍스트가 화면에 보인다. 즉, return 부분에 있는게 화면에 나오는것이다. 그러니
dongwookit.tistory.com
<html>
<head> </head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
'use strict';
// 남의 라이브러리 코드를 역추론하는게 매우 중요한 능력이다.
// React = {
// useState(value) {
// const setValue = (newValue) => {
// value = newValue; // 3. 객체를 함부로 바꾸지마라
// }
// return [value, setValue];
// }
// }
// 함수형 컴포넌트 x 함수 컴포넌트 O
// 함수 컴포넌트의 장점
// - 클래스 컴포넌트에 비해서 코드가 짧다.
// - 함수 컴포넌트 this 쓸 일이 없다.
function LikeButton() {
const [liked, setLiked] = React.useState(false); // 구조분해
// const result = React.useState(false);
// const liked = result[0];
// const setLiked = result[1];
// ▲ 구조분해 할당을 하지않으면 위 3줄과 같이해야한다.
// 뭔짓을 하든, 결국 return한게 화면이다.
if (liked) {
return 'You liked this';
}
return (
<button
onClick={() => {
setLiked(true);
}}
>
Like
</button>
);
}
</script>
<script type="text/babel">
ReactDOM.createRoot(document.querySelector('#root')).render(
<LikeButton />
);
</script>
</body>
</html>
function 컴포넌트는 class 컴포넌트와 다르게 render 라는 메서드가 없기 때문에 그냥 return 으로 화면을 그려주면 된다.
둘 다 뭔 짓을 하든 return 한 것이 화면이다.
클래스컴포넌트의 this.state와 대응 하는 useState를 쓰면 배열을 리턴하기 때문에 구조분해로 간편하게 처리하면 좋다.
함수 컴포넌트의 장점
- 클래스 컴포넌트에 비해 this 쓸 일이 없다.
- 클래스 컴포넌트에 비해 코드가 간결하다.
'Front end > React' 카테고리의 다른 글
클래스 컴포넌트의 형태와 리액트 데브툴즈 (0) | 2023.04.08 |
---|---|
가독성을 위한 JSX (0) | 2023.04.08 |
첫 리액트 컴포넌트(아직은 Class) (0) | 2023.04.08 |
리액트 array, object state 변경하는 법 (0) | 2023.04.06 |
리액트 useState (2) (0) | 2023.04.06 |