Props
컴포넌트의 속성(property)
부모 컴포넌트로부터 전달받은 값
= 컴포넌트가 최초 렌더링될 때에 화면에 출력하고자 하는 데이터를 담은 초기값으로 사용
객체 형태
= 어떤 타입의 값이라도 전달할 수 있도록
읽기 전용
= 외부로부터 전달받아 함부로 변경될 수 없다
Props
사용법
- 부모 컴포넌트에서 전달하고자 하는 데이터와 속성을 정의한다
- 정의된 값과 속성을 자식 컴포넌트에서 전달받는다
- 전달받은 props를 자식 컴포넌트에서 사용한다
<예> 다음과 같은 부모-자식 컴포넌트를 준비
function Parent() {
return (
<div className="parent">
<h1>I'm the parent</h1>
<Child />
</div>
);
};
function Child() {
return (
<div className="child"></div>
);
};
<Child attribute={value} />
와 같은 형식으로 정의한다
...
<h1>I'm the parent</h1>
<Child text={"I'm the eldest child"} />
...
속성은 text
, 전달할 데이터는 {"I'm the eldest child"}
...
function Child(props) {
return (
<div className="child"></div>
);
};
자식 컴포넌트의 인자로 props
를 주면
props
가 정의했던 모든 데이터를 가지고 온다
...
function Child(props) {
return (
<div className="child">
<p>{props.text}</p>
</div>
);
};
props
는 객체 : { key : value }
= props.key
로 props.value
를 사용할 수 있다
= 위에서 정의한 key
는 text
, value
는 "I'm the eldest child"
props.text
= "I'm the eldest child"
<예2> props
는 객체이므로 데이터 형태를 자유롭게 넣을 수 있다