React
[React] class 컴포넌트에서 함수 컴포넌트로 바꾸기
Alexim
2022. 6. 10. 00:58
1. class 컴포넌트
<script type="text/babel">
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = {liked: false};
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return (
<button onClick={() => {setLiked(true);}}>Like</button>
);
}
</script>
<script type="text/babel">
ReactDOM.render(<LikeButton />, document.querySelector("#root"));
</script>
2. 함수 컴포넌트
- this 쓸 일이 없다.
- 코드 짧고 가독성이 더 좋음
<script type="text/babel">
'use strict';
function LikeButton() {
const [liked, setLiked] = React.useState(false);
if (liked) {
return 'You liked this.';
}
return (
<button onClick={() => {setLiked(true);}}>Like</button>
);
}
</script>
<script type="text/babel">
ReactDOM.render(<LikeButton />, document.querySelector("#root"));
</script>
출처
https://www.youtube.com/watch?v=Sph9Pqi1Mz0