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 />
</>
'๐ Front > ๐ซ Typescript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Typescript] ํจ์ ์ฌ์ฉํ๊ธฐ (parameter, optional, rest, overloading) (0) | 2022.03.22 |
---|---|
[Typescript] ์ ํธ๋ฆฌํฐ ํ์ 12๊ฐ์ง ์ฌ์ฉํ๊ธฐ (0) | 2022.03.22 |
[Typescript]: type, interface, generics ์ฌ์ฉํ๊ธฐ (0) | 2021.09.06 |
Typescript ์์ฑ์, public, private (0) | 2021.09.06 |
Typescript: ์ค๊ธ(Type Aliases/Type Guard) (0) | 2021.09.06 |