props vs children
| 특징 | props | children |
|---|
| 정의 | 컴포넌트의 속성으로, 부모 컴포넌트에서 자식 컴포넌트로 전달하는 모든 데이터 | props의 특수한 속성으로, 부모가 자식 컴포넌트에 전달하는 자식 요소 |
| 용도 | 부모에서 자식 컴포넌트로 데이터를 전달 | 부모가 자식 컴포넌트의 콘텐츠를 동적으로 변경하기 위해 사용 |
| 형태 | 문자열, 숫자, 객체, 배열, 함수 등 다양한 형태 | JSX 요소나 다른 컴포넌트 등이 될 수 있음 |
| 기능 | 컴포넌트의 속성 값으로 전달된 데이터를 자식 컴포넌트가 사용 | 부모 컴포넌트가 자식 컴포넌트 내 콘텐츠를 동적으로 변경하여 컴포넌트를 재사용 가능하게 만듦 |
| 전달 방법 | 컴포넌트에 직접 속성으로 전달 | 자식 요소를 컴포넌트의 열려 있는 태그 안에 넣어서 전달 |
children을 활용한 컴포넌트
const FormControl = ({ label, htmlFor, sr_only, required, children }) => {
return (
<div className="FormControl">
<label htmlFor={htmlFor} className={sr_only}>
{label}
{required && <span className="required">*</span>}
</label>
{children} {}
</div>
);
};
export default FormControl;
<FormControl label={'이름'} htmlFor={'userName'} required>
<input
type="text"
id="userName"
name="userName"
placeholder="이름"
autoFocus
required
/>
</FormControl>
children이 아닌 다른 이름으로 사용하기
const FormControl = ({ label, htmlFor, sr_only, required, labelElement }) => {
return (
<div className="FormControl">
<label htmlFor={htmlFor} className={sr_only}>
{label}
{required && <span className="required">*</span>}
</label>
{inputElement} {}
</div>
);
};
export default FormControl;
<FormControl label={'이름'} htmlFor={'userName'} required inputElement={
<input
type="text"
id="userName"
name="userName"
placeholder="이름"
autoFocus
required
/>
} />