App.js // 최상위 컴포넌트
import { useEffect, useState } from "react";
import Component from "./component";
export default function App() {
const [getState, setState] = useState("");
const [getBoolean, setBoolean] = useState(false);
useEffect(() => {
if (getState !== "") {
console.log(getState);
}
}, [getState]);
useEffect(() => {
console.log(getBoolean);
}, [getBoolean]);
return (
<div className="App">
<Component setState={setState} setBoolean={setBoolean} />
</div>
);
}
하위 컴포넌트
import Component2 from "./component2";
export default function Component({ setState, setBoolean }) {
return (
<div className="component">
<input type="text" />
<button
style={{
width: 100,
height: 30,
marginLeft: 15
}}
>
버튼이얌 !!
</button>
<Component2 setState={setState} setBoolean={setBoolean} />
</div>
);
}
// 여기서도 바꿀 수 있고
최하위 컴포넌트
export default function Component({ setState, setBoolean }) {
return (
<div className="component2">
<input
type="text"
onChange={(e) => {
setState(e.target.value);
}}
/>
<button
style={{
width: 100,
height: 30,
marginLeft: 15
}}
onClick={() => {
setBoolean(true);
}}
>
버튼이얌2 !!
</button>
</div>
);
}
//최하위 까지 가능
또 다른 예시
parent components
--------------------------------------------
const [volume, setVolume] = useState(4);
function getVolume(value) {
setVolume(volume); 또는
console.log(value)
}
<child components getVolume={getVolume} />
---------------------------------------------
child components
function ChildComp({ getVolume }) {
function textFunc(e) {
getVolume(e.target.value);
}
return <input type="text" onChange={textFunc} />;
}
export default ChildComp;