컴포넌트 분리한 카운터웹 만들기
결과물
파일 구성
- components 폴더 생성
- components/Controller.js, viewers.js 파일 생성
코드 작성
App.js
- App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import "./styles.css";
import Viewers from "./components/Viewers";
import Controller from "./components/Controller";
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(1);
const handleSetCount = (value) => {
setCount(count + value);
};
return (
<div className="App">
<h1>Simple Counter</h1>
<section>
<Viewers count={count} />
</section>
<section>
<Controller handleSetCount={handleSetCount} />
</section>
</div>
);
}
Controller.js
- components/Controller.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const Controller = ({ handleSetCount }) => {
return (
<div>
<button onClick={() => handleSetCount(-1)}>-1</button>
<button onClick={() => handleSetCount(-10)}>-10</button>
<button onClick={() => handleSetCount(-100)}>-100</button>
<button onClick={() => handleSetCount(100)}>+100</button>
<button onClick={() => handleSetCount(10)}>+10</button>
<button onClick={() => handleSetCount(1)}>+1</button>
</div>
);
};
export default Controller;
Viewers.js
- components/Viewers.js
1
2
3
4
5
6
7
8
const Viewers = ({ count }) => {
return (
<div>
현재 카운트 :<h1>{count}</h1>
</div>
);
};
export default Viewers;
This post is licensed under
CC BY 4.0
by the author.