1. 컴포넌트의 정의
- 한 페이지를 구성하게 되는 작은 구성요소.
- 장점:
- 코드의 양이 줄어듦
- 개발 시간이 줄어듦
- 유지보수가 간편해짐
- 예시: hello와 world라는 component로 App.js를 구성하기
export default function Hello() {
return <div>Hello</div>;
}
export default function World(){
return <div>World</div>;
}
import Hello from './components/hello.js';
import World from './components/World.js';
function App () {
return(
<div>
<Hello></Hello>
<World/>
</div>
);
}
export defualt App;
2. props와 state
- props: 부모 component에서 자식 component로 전달되는 ‘읽기 전용’의 입력 데이터. 자식 component에서 수정이 불가능.
- state: component 자체가 가진 데이터. 읽기와 쓰기 모두 가능하며, setState를 활용해 값에 변화를 주어 component의 상태를 변환할 수도 있다.
- 예시: useState를 활용하여 increase버튼을 클릭할 때마다 value값이 1씩 증가하고, reset버튼을 누르면 값이 0이 되도록 만들기
import {useState} from "react";
function App (){
const [value, setValue] = useState(0);
return (
<div>
<h1>value: {value}</h1>
<button
onClick={() => {
console.log('increase value', value);
setValue(value + 1);
}}
>
Increase value
</button>
<button
onClick={() => {
setValue(0);
}}
>
Reset Value
</button>
</div>
);
}
export default App;
3. Class형 Component
import {Component} from "react";
export default class ClassComponent extends Component{
state = {
value: 0
};
constructor(props) {
super(props);
this.state = {
value: 1
};
}
resetValue() {
this.setState({value: 0});
}
render(){
return(
<div>
<h1>value: {this.state.value}</h1>
<button
onClick={()=>{
this.setState((state) => ({
value: state.value + 1
}));
}}
>
Increase value
</button>
<button
onClick={this.resetValue.bind(this)}
>
Reset Value
</button>
</div>
)
}
}
4. Component 실습:
- CourseCard.js의 Component인 CourseCard를, StudyFi.js에서 호출하여 데이터값을 집어넣고 스터디파이 강의 페이지를 만들어 보자.
export default function CourseCard({
img,
tags,
title,
salePercent,
monthlyPrice,
installmentMonth
}){
return (
<div className="CourseCard">
<div className="cover">
<img alt=""
src={img}
/>
</div>
<div className="info">
<ul className="tags">
{tags.map((item, idx) =>
<li key = {idx} className="tag">{item}</li>
)}
</ul>
<h4 className="name">{title}</h4>
<div className="prices">
<span className="sale-percent">{salePercent}%↓</span>
<span className="monthly-price">월 {monthlyPrice.toLocaleString()}원</span>
<span className="installment-month">/ {installmentMonth}개월</span>
</div>
</div>
</div>
);
}
import CourseCard from "./components/CourseCard";
function StudyFi () {
return(
<div style={{padding: 30}}>
<CourseCard
img = {"https://dst6jalxvbuf5.cloudfront.net/media/images/Course/cover_image/221020_172526/%E1%84%8F%E1%85%A9%E1%84%89%E1%85%B3%E1%84%8F%E1%85%A1%E1%84%83%E1%85%B3_%E1%84%92%E1%85%A1%E1%86%A8%E1%84%89%E1%85%B3%E1%86%B8%E1%84%8B%E1%85%A8%E1%84%8C%E1%85%A5%E1%86%BC_PC.png"}
tags = {['발표', '패키지', '최대할인']}
title = "비즈니스 올인원, 방구석 어학연수 패키지"
salePercent = {51}
monthlyPrice = {16583}
installmentMonth = {12}
/>
</div>
);
}
export default StudyFi;