๐Ÿ“† 22.11.13 - React Typescript ๋ฅผ ์“ฐ๋ฉด์„œ ์ด์ „๊ณผ ๋‹ฌ๋ผ์ง„ ์ ๋“ค. (ex. props)

๋ฒ„๋“คยท2022๋…„ 11์›” 12์ผ
0

โœจToday I Learn (TIL)

๋ชฉ๋ก ๋ณด๊ธฐ
16/62
post-thumbnail
post-custom-banner

์ด์ „์— ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ์—์„œ ์ž์‹ ์ปดํฌ๋„ŒํŠธ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋‹ฌํ•ด ์ค„ ๋•Œ ์‰ฝ๊ฒŒ ์ „ํ•ด์ฃผ์—ˆ๋˜ props๋„, ํƒ€์ž…์„ ์ •ํ•ด์ค˜์•ผ ๋  ๋ฟ๋”๋Ÿฌ, useState์œผ๋กœ ๋ฐ›๋Š” setState ๊ฐ’์—๋Š” ํŠน๋ณ„ํ•œ ํƒ€์ž…(?), ์ œ๋„ˆ๋ฆญ(?) ์„ ์ง€์ •ํ•ด์ค˜์•ผ ๋œ๋‹ค.

useState ๊ฐ’์„ props๋กœ ์ž์‹์—๊ฒŒ ์ „๋‹ฌํ•ด์ฃผ๊ธฐ

props๋กœ boolean ํƒ€์ž…์˜ useState ์นœ๊ตฌ๋“ค์„ ๋‚ด๋ ค์ค€๋‹ค๊ณ  ์ƒ๊ฐํ•ด๋ณด์ž.

const [isActive, setIsActive] = useState(false);

์œ„์™€ ๊ฐ™์ด isActive์— false ๋ผ๋Š” ๊ฐ’์„ ์ฃผ์—ˆ๊ธฐ์— ์œ„์˜ ๋ฐ์ดํ„ฐ๋“ค์˜ ํƒ€์ž…์€ boolean์ด ๋œ๋‹ค.

์ด์™€ ๊ฐ™์€ ๊ฐ’๋“ค์„ ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ์ธ Search ๋กœ ๋‚ด๋ ค์ฃผ๊ณ  ์‹ถ์–ด์„œ ์›๋ž˜ ํ•˜๋˜๋ฐ๋กœ ํ•˜๊ฒŒ๋˜๋ฉด ํƒ€์ž…์—๋Ÿฌ๋ฅผ ๋งˆ์ฃผ์น˜๊ฒŒ ๋  ๊ฒƒ์ด๋‹ค.

//!! type error !!
<Search isActive={isActive} setIsActive={setIsActive} />

์ •ํ™•ํ•œ ์ด์œ ๋Š” ์ž˜ ๋ชจ๋ฅด๊ฒ ์ง€๋งŒ, ์•„๋งˆ ์ž์‹ ์ปดํฌ๋„ŒํŠธ์—์„œ ์ด๋“ค์˜ ํƒ€์ž…์„ ๋ฐ›์„ ์ค€๋น„๊ฐ€ ์•ˆ๋˜์–ด์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋ผ๊ณ  ์ƒ๊ฐํ•œ๋‹ค. ๋‚˜๋Š” ์ด๋ฏธ useState ๋‹จ๊ณ„์—์„œ boolean ์„ ์ง€์ •ํ•˜๊ฒŒ ํ•ด์ค˜์„œ ์•Œ์•„์„œ ์ธ์‹์„ ํ•  ๊ฒƒ์ด๋ผ๊ณ  ์—ฌ๊ฒผ๋Š”๋ฐ, ๊ทธ๊ฒƒ์ด ์•„๋‹Œ๊ฐ€๋ณด๋‹ค.

๊ทธ๋ ‡๋‹ค๋ฉด ์ด๋ฒˆ์—” props๋ฅผ ๋ฐ›์„ ์ž์‹ ์ปดํฌ๋„ŒํŠธ์—์„œ interface๋กœ ๋ฌด์Šจ type์ด ์ง€์ •๋  ๊ฒƒ์ธ์ง€ ์„ค์ •ํ•ด ๋ณด๋ ค๊ณ  ํ•œ๋‹ค.

interface isProps {
  isActive: boolean;
  // type error!
  setIsActive: boolean
}

isActive๊ฐ€ boolean ๊ฐ’์ด๋ผ๋Š” ๊ฒƒ๋„ ์•Œ๊ณ  setIsActive๋„ ๊ฒฐ๊ตญ boolean์˜ ํ˜•ํƒœ๋ฅผ ๋„์šธ ๊ฒƒ์ด๋ผ๊ณ  ์ƒ๊ฐํ–ˆ๊ธฐ์— ์ด๋ฆฌ ์ง€์ •์„ ํ•˜๊ณ  props๋ฅผ ์‚ฌ์šฉํ•˜๋ คํ–ˆ๋Š”๋ฐ ํƒ€์ž…์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋‹ค.

์ „์ง€์ „๋Šฅํ•œ Stackoverflow์—์„œ ์ด๋ฅด๊ธธ, setIsActive ๊ฐ™์€ setState๋“ค์€ ํŠน๋ณ„ํ•œ ํƒ€์ž…? ์ œ๋„ˆ๋ฆญ? ์„ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค๊ณ  ํ•œ๋‹ค..! ๋ฐ”๋กœ ์•„๋ž˜์™€ ๊ฐ™์ด

interface isProps {
  isActive: boolean;
  setIsActive: React.Dispatch<React.SetStateAction<boolean>>;
}

์ด๋ ‡๊ฒŒ ํ•˜๊ณ  ์‚ฌ์šฉํ•  ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ์—์„œ isProps์˜ ํƒ€์ž…๊ฐ’์œผ๋กœ ํ˜ธ์ถœํ•˜๋‹ˆ ์ž˜ ์ž‘๋™์ด ๋œ๋‹ค.

function Search({ isActive, setIsActive }: isProps) {
  /* SearchModal ์ž‘๋™ boolean */
  const ModalHandler = () => {
    setIsActive(!isActive);
  };
profile
ํƒœ์–ด๋‚œ ๊น€์— ๋งŽ์€ ๊ฒฝํ—˜์„ ํ•˜๋ ค๊ณ  ์•„๋“ฑ๋ฐ”๋“ฑ ์• ์“ฐ๋Š” ํ”„๋ก ํŠธ์—”๋“œ ๊ฐœ๋ฐœ์ž
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€