Props
필요성
역할
- 상태를 위로 끌어올리기
- 필요할때 자식에게 내려보내기
사용법
<AppChild name={name} age={age}/>
export default function AppChild({ name, age })
useState
<AppChild name={name} age={age} onChangeName={(newName) => setName(newName)}/>
<button onClick={() => onChangeName("tom")} >이름 바꾸기</button>
예시
이름 나이 예제
export default function App(){
const [name, setName] = useState("david");
const [age, setAge] = useState(15);
return (
<>
<h1>App</h1>
<p>{name}</p>
<p>{age}</p>
<AppChild name={name} age={age}/>
</>
);
}
export default function AppChild({ name, age }) {
return (
<>
<h2>AppChild</h2>
<p>{name}</p>
<p>{age}</p>
<GrandChild />
</>
);
}
치킨 소금 예제
import FriedChicken from "./components/FriedChicken";
export default function App(){
const [title, setTitle] = useState("치킨은 맛있다.");
const [salt, setSalt] = useState(30);
return (
<>
<h1>App</h1>
<p>{title}</p>
<p>{salt}</p>
<FriedChicken title={title} salt={salt} onChangeSalt={(newSalt) => setSalt(newSalt)}/>
</>
);
}
import ChickenChild from "./ChickenChild";
export default function FriedChicken({title, salt, onChangeSalt}){
return (
<>
<h2>FriedChicken</h2>
<p>{title}</p>
<p>{salt}</p>
<ChickenChild title={title} salt={salt} onChangeSalt={onChangeSalt}/>
</>
);
}
export default function ChickenChild({title, salt, onChangeSalt}) {
return (
<>
<h3>ChickenChild</h3>
<p>{title}</p>
<p>{salt}</p>
<button onClick={() => onChangeSalt(20)}>소금을 줄이자</button>
</>
);
}
연결문서
댓글남기기