본문 바로가기
Frontend/React

[React] 컴포넌트의 재사용성 (Wrap)

by 민두이 2023. 2. 4.
728x90
반응형

자식 요소들을 감싸는 한단계 높은 부모 컴포넌트를 만들면 컴포넌트를 효율적으로 재사용 할 수 있음

컴포넌트를 재사용함에 있어 그 아래 내용들을 전달할 때에 children이라는 props로 전달하여 사용

 

  • 사용 예시
export default function AppWrap() {
    return (
        <div>
            <Navbar>
                <Avatar
                image='https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=686&q=80'
                name='linda'
                size={300}
                />
            </Navbar>
        </div>
    );
}


function Navbar ({children}) {
    return (
        <header style={{backgroundColor:'yellow'}}>
            {children}
        </header>
    )
}

function Avatar ({image, name, size}) {
    return (
        <>
         <img
            src={image}
            alt={name}
            width={size}
            height={size}
            style={{borderRadius:'50%'}}
          />
        </>
    )
}

 

 

728x90