부모 컴포넌트가 자식 컴포넌트에게 물려준 데이터 -> 컴포넌트 간의 정보 교류 방법
Mother
컴포넌트에서 mother
코드가 있는데, child
에서는 지금 mother의 이름
을 모르는 상태이다.
import React from "react";
function App() {
return <GrandFather />;
}
function GrandFather() {
return <Mother />;
}
function Mother() {
const name = '홍부인';
return <Child />;
}
function Child() {
return <div>연결 성공</div>;
}
export default App;
Mother
컴포넌트가 가지고 있는 정보를 child
에게 주고 싶을때,
motherName
이라는 이름으로 name
값을 child
컴포넌트에 전달해준다.
import React from "react";
function App() {
return <GrandFather />;
}
function GrandFather() {
return <Mother />;
}
function Mother() {
const name = '홍부인';
return <Child motherName={name} />; // 💡"props로 name을 전달했다."
}
function Child() {
return <div>연결 성공</div>;
}
export default App;
mother
이 전달해준 motherName
은
function Child(props){
console.log(props)
return <div>연결 성공</div>
}
이렇게 props의 값
을 받아 올 수 있다.
mother
로부터 전달받은 motherName
을 화면에 렌더링
import React from "react";
function Child(props) {
return <div>{props.motherName}</div>;
}
function Mother() {
const name = "홍부인";
return <Child motherName={name} />;
}
function GrandFather() {
return <Mother />;
}
function App() {
return <GrandFather />;
}
export default App;
props도 object literal
의 형태이기 때문에 {props.motherName}
으로 사용
object literal의 key
가 mothrName
인 이유는 child
로 보내줄 때 motherName = {name}
으로 보내주었기 때문이다.