Props란?
- 컴포넌트의 속성(property)를 의미
- 성별이나 이름과 같이 변하지 않는 값
- 외부로부터 전달 받는 값
- 변경될 수 없는 읽기 전용(read-only)객체
- 읽기 전용 객체가 아니라면 props를 전달받은 하위 컴포넌트 내에서 props 를 직접 수정 시 props를 전달한 상위 컴포넌트의 값에 영향
- 개발자가 의도하지 않은 side effect 방지
- React의 단방향, 하향식 데이터 흐름 원칙(React is all about one-way data flow down the component hierarchy)에 위배 방지
- 부모 컴포넌트(상위 컴포넌트)로 부터 전달받은 값
- React 컴포넌트는 JavaScript 함수와 클래스로, props를 함수의 전달인자(arguments)처럼 전달받아 이를 기반으로 화면에 어떻게 표시되는지를 기술하는 React 엘리먼트를 반환값
- 컴포넌트가 최초 렌더링될 때에 화면에 출력하고자 하는 데이터를 담은 초기값으로 사용
- 객체 형태
사용방법
function Parent() {
return (
<div className="parent">
<h1>I'm the parent</h1>
<Child />
</div>
);
};
function Child() {
return (
<div className="child"></div>
);
};
- 하위 컴포넌트에 전달하고자 하는 값(data)과 속성을 정의
<Child attribute={value} />
<Child text={"I'm the eldest child"} />
- props를 이용하여 정의된 값과 속성을 전달
function Parent() {
return (
<div className="parent">
<h1>I'm the parent</h1>
<Child>I'm the eldest child</Child>
</div>
);
};
function Child(props) {
return (
<div className="child"></div>);
};
- 전달받은 props를 렌더링
function Child(props) {
return (
<div className="child">
<p>{props.children}</p>
</div>
);
};
function Child(props) {
return (
<div className="child">
<p>{props.text}</p>
</div>);
};