부모 컴포넌트가 자식 컴포넌트에게 물려준 데이터 -> 컴포넌트 간의 정보 교류 방법
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}으로 보내주었기 때문이다.