Jieunny์˜ ๋ธ”๋กœ๊ทธ

S2) Unit 9. [React] React ๋ฐ์ดํ„ฐ ํ๋ฆ„ ๋ณธ๋ฌธ

CodeStates/learning contents

S2) Unit 9. [React] React ๋ฐ์ดํ„ฐ ํ๋ฆ„

Jieunny 2023. 2. 2. 10:32

๐Ÿ“ฃ  React ๋ฐ์ดํ„ฐ ํ๋ฆ„

โœ”๏ธ ์ปดํฌ๋„ŒํŠธ๋Š” ์ปดํฌ๋„ŒํŠธ ๋ฐ”๊นฅ์—์„œ props๋ฅผ ์ด์šฉํ•ด ๋ฐ์ดํ„ฐ๋ฅผ ๋งˆ์น˜ ์ „๋‹ฌ์ธ์ž(arguments) ํ˜น์€ ์†์„ฑ(arributes)์ฒ˜๋Ÿผ ์ „๋‹ฌ๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

โžฐ ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋‹ฌํ•˜๋Š” ์ฃผ์ฒด๋Š” ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ -> ๋ฐ์ดํ„ฐ ํ๋ฆ„์ด ํ•˜ํ–ฅ์‹์ด๋‹ค.

โžฐ React๋Š” ๋‹จ๋ฐฉํ–ฅ ๋ฐ์ดํ„ฐ ํ๋ฆ„์ด๊ณ , ์ปดํฌ๋„ŒํŠธ๋Š” props๋ฅผ ํ†ตํ•ด ์ „๋‹ฌ๋ฐ›์€ ๋ฐ์ดํ„ฐ๊ฐ€ ์–ด๋””์„œ ์™”๋Š”์ง€ ์•Œ์ง€ ๋ชปํ•œ๋‹ค.

โžฐ ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ์—์„œ์˜ ์ƒํƒœ๊ฐ€ ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ์— ์˜ํ•ด ๋ณ€ํ•˜๋Š” ๊ฒƒ์ด ์—ญ๋ฐฉํ–ฅ ๋ฐ์ดํ„ฐ ํ๋ฆ„์ฒ˜๋Ÿผ ๋ณด์ผ ์ˆ˜ ์žˆ๋‹ค.

โžฐ ์ด๋ฅผ ์œ„ํ•ด์„œ Stste ๋Œ์–ด์˜ฌ๋ฆฌ๊ธฐ(Lifting state up) ์„ ์ด์šฉํ•œ๋‹ค.

 

๐Ÿ“ฃ  State ๋Œ์–ด์˜ฌ๋ฆฌ๊ธฐ(Lifting state up)

โžฐ ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ์˜ '์ƒํƒœ๋ฅผ ๋ณ€๊ฒฝํ•˜๋Š” ํ•จ์ˆ˜' ๊ทธ ์ž์ฒด๋ฅผ ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ๋กœ ์ „๋‹ฌํ•˜๊ณ , ์ด ํ•จ์ˆ˜๋ฅผ ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์‹คํ–‰ํ•œ๋‹ค.

-> ์—ฌ์ „ํžˆ ๋‹จ๋ฐฉํ–ฅ ๋ฐ์ดํ„ฐ ํ๋ฆ„์˜ ์›์น™์— ๋ถ€ํ•ฉํ•œ๋‹ค.

function ParentComponent() {
  const [value, setValue] = useState("๋‚  ๋ฐ”๊ฟ”์ค˜!");

  const handleChangeValue = () => {
    setValue("๋ณด์—ฌ์ค„๊ฒŒ ์™„์ „ํžˆ ๋‹ฌ๋ผ์ง„ ๊ฐ’");
  };

  return (
    <div>
      <div>๊ฐ’์€ {value} ์ž…๋‹ˆ๋‹ค</div>
      <ChildComponent handleButtonClick={handleChangeValue}  />	//	props๋กœ ํ•จ์ˆ˜๋ฅผ ๋„˜๊ฒจ์ค€๋‹ค.
    </div>
  );
}

function ChildComponent({ handleButtonClick }) {	// props๋กœ ํ•จ์ˆ˜๋ฅผ ์ „๋‹ฌ๋ฐ›๋Š”๋‹ค.
  const handleClick = () => {
    // Q. ์ด ๋ฒ„ํŠผ์„ ๋ˆŒ๋Ÿฌ์„œ ๋ถ€๋ชจ์˜ ์ƒํƒœ๋ฅผ ๋ฐ”๊ฟ€ ์ˆœ ์—†์„๊นŒ?
    // A. ์ธ์ž๋กœ ๋ฐ›์€ ์ƒํƒœ ๋ณ€๊ฒฝ ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•˜์ž!

    handleButtonClick()	// props๋กœ ์ „๋‹ฌ๋ฐ›์€ ํ•จ์ˆ˜๋ฅผ ์ปดํฌ๋„ŒํŠธ ๋‚ด์—์„œ ์‹คํ–‰ํ•œ๋‹ค.
  }

  return (
    <button onClick={handleClick}>๊ฐ’ ๋ณ€๊ฒฝ</button>
  )
}

//ํ•„์š”์— ๋”ฐ๋ผ ์„ค์ •ํ•  ๊ฐ’์„ ์ฝœ๋ฐฑ ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ๋„˜๊ธธ ์ˆ˜๋„ ์žˆ๋‹ค.

function ParentComponent() {
  const [value, setValue] = useState("๋‚  ๋ฐ”๊ฟ”์ค˜!");

  const handleChangeValue = (newValue) => {
    setValue(newValue);
  };

  // ...์ƒ๋žต...
}

function ChildComponent({ handleButtonClick }) {
  const handleClick = () => {
    handleButtonClick('๋„˜๊ฒจ์ค„๊ฒŒ ์ž์‹์ด ์›ํ•˜๋Š” ๊ฐ’')
  }

  return (
    <button onClick={handleClick}>๊ฐ’ ๋ณ€๊ฒฝ</button>
  )
}