์žฌ๋ฐŒ๊ฒŒ ํ•ฉ์‹œ๋‹ค

๊ธฐ๋กํ•˜๊ธฐ, ๊ฐ€์‹œํ™”ํ•˜๊ธฐ

Typescript

React.FC ๋Œ€์‹  PropsWithChildren์„ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š” ์ด์œ 

์€๋˜๋”” 2022. 11. 17. 13:20

React.FC์˜ ๋ฌธ์ œ์ 

props์—๋Š” ๋‘ ์ข…๋ฅ˜๊ฐ€ ์žˆ๋‹ค.

  • ๋ช…์‹œ์  props: props ํƒ€์ž…์— ๋ช…์‹œ์ ์œผ๋กœ ์ž‘์„ฑ๋˜์–ด ์žˆ๋Š” props
  • ์•”์‹œ์  props:@types/react๋“ฑ์— ์˜ํ•ด ์ž๋™์ ์œผ๋กœ ์ถ”๊ฐ€๋˜๋Š” props

React.FC์˜ props๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ children์„ ํฌํ•จํ•œ๋‹ค. ์ฆ‰, React.FC๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ children์ด ์•”์‹œ์  props๊ฐ€ ๋œ๋‹ค.

 

excess props: ์ปดํฌ๋„ŒํŠธ์— ๋„˜๊ฒจ์ง€์ง€๋งŒ ์ปดํฌ๋„ŒํŠธ์—์„œ ์‚ฌ์šฉ๋˜์ง€ ์•Š๋Š” props

→ excess props์˜ ์กด์žฌ๋Š” POLA์›์น™์„ ์–ด๊ธฐ๊ฒŒ ๋งŒ๋“ ๋‹ค.

POLA: Principle of Least Astonishment ์ปดํฌ๋„ŒํŠธ๋Š” ์‚ฌ์šฉ์ž๊ฐ€ ์˜ˆ์ƒํ•œ๋Œ€๋กœ ์ž‘๋™ํ•ด์•ผ ํ•œ๋‹ค๋Š” ์›์น™

 

์•”์‹œ์  props์ธ children์€ excess props์— ํ•ด๋‹นํ•œ๋‹ค. ์‚ฌ์šฉ์ž ๋ชจ๋ฅด๊ฒŒ ์ปดํฌ๋„ŒํŠธ์˜ props๋กœ ๋„˜๊ฒจ์ง€๊ธฐ ๋•Œ๋ฌธ์—, ์ปดํฌ๋„ŒํŠธ์˜ ์˜ˆ์ธก ๋ถˆ๊ฐ€๋Šฅํ•œ ๋™์ž‘์„ ์•ผ๊ธฐํ•  ์ˆ˜ ์žˆ๋‹ค.

// ์˜ˆ์‹œ
const App: React.FC = () => { /*... */ };
const Example = () => {
	<App><div>Unwanted children</div></App>
}

๋”ฐ๋ผ์„œ children prop์„ ๋ช…์‹œํ•ด์ฃผ๋Š” ๊ฒƒ์ด ๋ฐ”๋žŒ์งํ•˜๋‹ค.

 

ํ•ด๊ฒฐ๋ฐฉ์•ˆ

React.PropsWithChildren<T>์„ ์‚ฌ์šฉํ•œ๋‹ค.

type PropsWithChildren<P = unknown> = P & { children?: ReactNode | undefined };

๋‚ด๊ฐ€ ๋„˜๊ธด props ํƒ€์ž…์— children์„ ์ถ”๊ฐ€ํ•œ ํƒ€์ž…์„ ๋ฆฌํ„ดํ•œ๋‹ค. ์ด๋ฅผ ํ†ตํ•ด children ์„ ๋ช…์‹œ์  props๋กœ ๋„˜๊ฒจ์ค„ ์ˆ˜ ์žˆ๋‹ค.

 

์‚ฌ์šฉ๋ฐฉ๋ฒ•

// ์‚ฌ์šฉ๋ฐฉ๋ฒ•1: ๋‚ด๊ฐ€ ์ •์˜ํ•œ props ํƒ€์ž…๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ

interface MyProp {
	foo: any;
}

function App(props: React.PropsWithChild<MyProp>) {
	return <div>{props.children}</div>
}

// ์‚ฌ์šฉ๋ฐฉ๋ฒ•2: children prop๋งŒ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ

function App({children}: React.PropsWithChildren) => {
	...
}