
모든 리액트 컴포넌트는 key와 ref 속성 포함, children 속성은 선택적으로 포함
interface Attributes {
key? : Key | null | undefined;
}
type Key = string | number;
key 속성은 반드시 설정하지 않아도 되며, 문자열이나 숫자를 설정해야 함.
그러나 아래와 같이 같은 태그가 있는 경우 key로 구분할 것을 요청
src.App.tsx key속성이 없다는 경고 메세지가 출력됨
export default function App(){
const texts = [<p>hello</p>, <p>world</p>]
return <div>{texts}</div>
}
src.App.tsx key속성을 주어 해결, map함수 이용
export default function App(){
const texts = [<p key="1">hello</p>, <p key="2">world</p>]
return <div>{texts}</div>
}
export default function App(){
const texts = ['hello','world'].map((text, index) => <p key={index}>{text}</p>)
return <div>{texts}</div>
}
children? : ReactNode | undefined;
children 속성은 값을 설정하지 않아도 되는 선택 속성
children은 <div>처럼 자식 요소를 포함할 수 있는 컴포넌트에서만 사용 가능
src/P.tsx
import type{FC, ReactNode} from 'react'
export type PProps = {
children? : ReactNode
}
const P : FC<PProps> = props => {
return <p {...props}/>
// const {children} = props
// return <p children={children}/>
}
export default P
src/App.ts
import P from './P'
export default function App(){
const texts = ['hello','world'].map((text, index) => <P key={index}>{text}</P>)
return <div>{texts}</div>
}
리액트 18버전부터 FC타입에 children속성을 제거하여, **PropsWithChildren** 제네릭 타입 제공
children? : ReactNode → PropsWithChildren 전환
src/P.tsx
import type{FC, PropsWithChildren} from 'react'
export type PProps = {}
const P : FC<PropsWithChildren<PProps>> = props => {
return <p {...props}/>
// const {children} = props
// return <p children={children}/>
}
export default P