[practice] props

이아현·2025년 2월 6일
0

TypeScript

목록 보기
4/6

// App.tsx

import CourseGoal from "./components/CourseGoal.tsx"
import Header from "./components/Header.tsx"
import goalsImg from "./assets/goals.jpg"

export default function App() {
	return (
    	<main>
        	<Header image={{src: goalsImg, alt: "A list of goals"}}/>
            	<h1>Master TypeScript!</h1>
            </Header>
            <CourseGoal title="Learn TypeScript">
            	<p>Learn it from the ground</p>
            </CourseGoal>
        </main>
    )
}
  • Header 컴포넌트에 src, alt, <h1>태그를 props로 전달

// Header.tsx

  • <h1>태그의 경우 children이기 때문에 ReactNode로 타입 지정
  • srcalt의 경우 image를 키값으로 갖는 객체 안의 값이기 때문에 image객체 안에 타입 지정
  • Header컴포넌트에 HeaderProps를 선언
  • 해당 값을 가져와서 사용
type HeaderProps = {
	image: {
    	src: string;
        alt: string;
    };
	children: ReactNode
}

export default function Header({image, children} : HeaderProps) {
	return (<header>
    	<img src={image.src} alt={image.alt}/>
        // <img {...image}/>
        {children}
    </header>)
}
profile
PM을 지향하는 FE 개발자 이아현입니다 :)

0개의 댓글