๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ

 

1. ์ฝ”๋“œ ๊ฐ€๋…์„ฑ

const Greeting:FC<GreetingProps> = function({ name }) {
  return <h1>Hello {name}</h1>
}
function Greeting({ name }: GreetingProps) {
  return <h1>Hello {name}</h1>
}

๊ตณ์ด FC type์„ ๋ช…์‹œํ•ด์ค˜์„œ ์ฝ”๋“œ ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ง„๋‹ค.

 

2. FC<> always imply children

export const Greeting:FC<GreetingProps> = ({ name }) => {
  // name is string!
  return <h1>Hello {name}</h1>
};

// use it in the app
const App = () => <>
  <Greeting name="Stefan">
    <span>{"I can set this element but it doesn't do anything"}</span>
  </Greeting>
</>

React.FC๋Š” ์•”๋ฌต์ ์œผ๋กœ children prop์„ ๋‚ด์žฅํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์œ„์™€ ๊ฐ™์ด children prop์„ ์ง€์ •ํ•˜์ง€ ์•Š๋”๋ผ๋„ ์œ„ ์ฝ”๋“œ๋Š” ์˜ค๋ฅ˜์—†์ด ๋™์ž‘ํ•œ๋‹ค.

function Greeting({ name }: GreetingProps) {
  return <h1>Hello {name}</h1>
}
const App = () => <>
  <Greeting name="Stefan">
    {/* The next line throws errors at me! ๐Ÿ’ฅ*/}
    <span>{"I can set this element but it doesn't do anything"}</span>
  </Greeting>
</>

์ด๋Ÿฐ ๊ฒฝ์šฐ๋Š” helper Type์„ ์‚ฌ์šฉํ•˜์—ฌ ์ปดํฌ๋„ŒํŠธ์— prop์„ ์ถ”๊ฐ€ํ•˜์—ฌ ์‚ฌ์šฉํ•œ๋‹ค.

type WithChildren<T = {}> = 
  T & { children?: React.ReactNode };

type CardProps = WithChildren<{
  title: string
}>

function Card({ title, children }: CardProps) {
  return <>
    <h1>{ title }</h1>
    {children}
  </>
}

์ด์œ ๋Š” ํŠน์ • ์ปดํฌ๋„ŒํŠธ์—์„œ๋Š” children ํ•„์š” ํ• ์ˆ˜๋„ ํ•˜์ง€ ์•Š์„ ์ˆ˜๋„ ์žˆ๋Š”๋ฐ, React.FC ๋Š” children ์„ ์˜ต์…”๋„ ํƒ€์ž…์œผ๋กœ ์ง€์ •ํ•ด๋†จ๊ธฐ์— ์ด๋Š” ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์˜ ์ฒ ํ•™๊ณผ๋Š” ๋ชจํ˜ธํ•œ ๊ด€๊ณ„๋ฅผ ๋„๊ฒŒ ๋œ๋‹ค.

๋”ฐ๋ผ์„œ ํŠน์ • ์ปดํฌ๋„ŒํŠธ์—์„œ children ์„ ํ•„์š”๋กœ ํ•œ๋‹ค๋ฉด ๋ฐ˜๋“œ์‹œ children ํƒ€์ž…์„ ๋ช…์‹œํ•ด์•ผํ•œ๋‹ค.
react.fc๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด children์„ ๋ช…์‹œํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— props๊ฒฐ๊ณผ ์ ์œผ๋กœ ์ฐจ๋ผ๋ฆฌ, React.FC ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  GreetingsProps ํƒ€์ž…์„ ํ†ตํ•ด children์ด ์žˆ๋‹ค ์—†๋‹ค๋ฅผ ๋ช…๋ฐฑํ•˜๊ฒŒ ๋ช…์‹œํ•˜๋Š”๊ฒŒ ๋œ ํ—ท๊ฐˆ๋ฆฐ๋‹ค.

 

defaultProps

defaultProps๋Š” class๊ธฐ๋ฐ˜ React์—์„œ prop์˜ default๊ฐ’์„ ์ง€์ •ํ•ด์ฃผ๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•œ๋‹ค.

type LoginMsgProps = { 
    name?: string;
    }; 

function LoginMsg({ name = "Guest" }: LoginMsgProps) {
    return <p>Logged in as {name}</p>; 
    }

ํ•˜์ง€๋งŒ React.FC๋Š” defaultProps๋ฅผ ์—ฐ๊ฒฐ์„ ๋Š๊ณ  props์œผ๋กœ ๋“ค์–ด์˜จ ๊ธฐ๋ณธ๊ฐ’์œผ๋กœ ์‚ฌ์šฉํ•œ๋‹ค.

export const Greeting:FC<GreetingProps> = ({ name }) => { 
    // name is string!
    return <h1>Hello {name}</h1>
};

Greeting.defaultProps = { name: "World" };

const App = () =>
    <>
    {/* Big boom ๐Ÿ’ฅ*/} 
    <Greeting />
   </>

React.FC ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ์˜ค๋ฅ˜์—†์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

export const Greeting = ({ name }: GreetingProps) => {
    // name is string!
    return <h1>Hello {name}</h1> 
}; 

Greeting.defaultProps = { name: "World" };

const App = () => 
    <>
        {/* Yes! โœ… */}
        <Greeting />
    </>
๋ฐ˜์‘ํ˜•