변경에 따라 컴포넌트가 랜더링 되어야 한다 == state

App.jsx에 state 생성 및 자식 컴포넌트로 전달
import "./App.css";
import Viewer from "./components/Viewer";
import Controller from "./components/Controller";
import { useState } from "react";
function App() {
const [count, setCount] = useState;
return (
<div className="App">
<h1>Simple Counter</h1>
<section>
<Viewer count={count} />
</section>
<section>
<Controller />
</section>
</div>
);
}
export default App;
Viwer 컴포넌트 수정
const Viewer = ({ count }) => {
return (
<div>
<div>현재 카운트 :</div>
<h1>{count}</h1>
</div>
);
};
export default Viewer;
App.jsx에서 버튼 클릭시 동작할 이벤트 핸들러 작성 및 Controller에 전달
import "./App.css";
import Viewer from "./components/Viewer";
import Controller from "./components/Controller";
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
const onClickButton = (value) => {
setCount(count + value);
};
return (
<div className="App">
<h1>Simple Counter</h1>
<section>
<Viewer count={count} />
</section>
<section>
<Controller onClickButton={onClickButton} />
</section>
</div>
);
}
export default App;
Controller 컴포넌트 수정
const Controller = ({ onClickButton }) => {
return (
<div>
<button
onClick={() => {
onClickButton(-1);
}}
>
-1
</button>
<button
onClick={() => {
onClickButton(-10);
}}
>
-10
</button>
<button
onClick={() => {
onClickButton(-100);
}}
>
-100
</button>
<button
onClick={() => {
onClickButton(+100);
}}
>
+100
</button>
<button
onClick={() => {
onClickButton(+10);
}}
>
+10
</button>
<button
onClick={() => {
onClickButton(+1);
}}
>
+1
</button>
</div>
);
};
export default Controller;
결과

최종정리


