[React] props vs children

zzincode·2025년 2월 21일

React

목록 보기
17/20

props vs children

특징propschildren
정의컴포넌트의 속성으로, 부모 컴포넌트에서 자식 컴포넌트로 전달하는 모든 데이터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
  />
} />

0개의 댓글