๊ด€๋ฆฌ ๋ฉ”๋‰ด

JiYoung Dev ๐Ÿ–ฅ

[React] ์ฐธ์ฐธ์ฐธ ๊ฒŒ์ž„ ๋งŒ๋“ค๊ธฐ (2023.05.26) ๋ณธ๋ฌธ

full stack/React

[React] ์ฐธ์ฐธ์ฐธ ๊ฒŒ์ž„ ๋งŒ๋“ค๊ธฐ (2023.05.26)

Shinjio 2023. 5. 29. 16:45

๐ŸŽˆ ์ฐธ์ฐธ์ฐธ ๊ฒŒ์ž„ ๋งŒ๋“ค๊ธฐ

 

 

๐Ÿ“– ๊ฒŒ์ž„๊ทœ์น™

1. ๋‚˜๋Š” ๊ณต๊ฒฉ, ์ปดํ“จํ„ฐ๋Š” ์ˆ˜๋น„ ๋‹ด๋‹น

2. ๋‚ด๊ฐ€ ๋ฒ„ํŠผ์„ ํด๋ฆญํ–ˆ์„ ๋•Œ ๋‚˜์™€ ์ปดํ“จํ„ฐ์˜ ์„ ํƒ์ด ๊ฐ™๋‹ค๋ฉด ๋‚˜(๊ณต๊ฒฉ)์˜ ์Šน๋ฆฌ

3. ๋‚˜์™€ ์ปดํ“จํ„ฐ์˜ ์„ ํƒ์ด ๋‹ค๋ฅด๋‹ค๋ฉด ์ปดํ“จํ„ฐ(์ˆ˜๋น„)์˜ ์Šน๋ฆฌ

 

๐Ÿ“– ์ž‘์„ฑ์ฝ”๋“œ

 

import React, { useState, useEffect } from "react";

const Ex03 = () => {
  /**
   * ์ฐธ์ฐธ์ฐธ ๊ฒŒ์ž„์„ ๋งŒ๋“ค์–ด๋ณด์ž!
   * ๊ฒŒ์ž„ ๊ทœ์น™
   * 1. ๋‚˜๋Š” ๊ณต๊ฒฉ, ์ปดํ“จํ„ฐ๋Š” ์ˆ˜๋น„๋ฅผ ๋‹ด๋‹น
   * 2. ๋‚ด๊ฐ€ ๋ฒ„ํŠผ์„ ํด๋ฆญํ–ˆ์„ ๋•Œ ๋‚˜์™€ ์ปดํ“จํ„ฐ์˜ ์„ ํƒ์ด ๊ฐ™๋‹ค๋ฉด ๋‚˜(๊ณต๊ฒฉ)์˜ ์Šน๋ฆฌ
   * 3. ๋‚˜์™€ ์ปดํ“จํ„ฐ์˜ ์„ ํƒ์ด ๋‹ค๋ฅด๋‹ค๋ฉด ์ปดํ“จํ„ฐ(์ˆ˜๋น„)์˜ ์Šน๋ฆฌ
   *
   * ๋ฌธ์ œํ’€์ด
   * 1. ํ•„์š”ํ•œ state๋“ค์„ ๊ด€๋ฆฌ : ๋‚ด์„ ํƒ, ์ปดํ“จํ„ฐ์„ ํƒ, ๊ฒŒ์ž„๊ฒฐ๊ณผ
   *     >> useState
   * 2. ๋‚ด ์„ ํƒ >> ๋‚ด๊ฐ€ ๋ˆ„๋ฅธ ๋ฒ„ํŠผ์˜ ๋‚ด์šฉ์„ ์„ ํƒ์œผ๋กœ ์‚ผ๋Š”๋‹ค.
   *     >> ์ด๋ฒคํŠธ ๊ฐ์ฒด
   * 3. ์ปดํ“จํ„ฐ ์„ ํƒ >> ๋žœ๋คํ•˜๊ฒŒ ๋ฐ›์•„์˜ฌ ๊ฒƒ(pos๋ผ๋Š” ๋ฐฐ์—ด์—์„œ)
   *     >> ๋‚œ์ˆ˜ ๋ฝ‘๊ธฐ
   * 4. ๋งŒ์•ฝ ๋‚˜์˜ ์„ ํƒ์— ํ•ด๋‹นํ•˜๋Š” state๊ฐ’์ด ๋ณ€ํ•œ๋‹ค๋ฉด (๊ฒŒ์ž„ ์‹œ์ž‘),
   *      ์ŠนํŒจ๋ฅผ ํŒ๋ณ„ํ•ด ์ค„ ๊ฒƒ
   *     >> useEffect
   * 5. ๊ฒŒ์ž„์ด ์‹œ์ž‘ํ•˜๊ธฐ ์ „์—๋Š” "๊ฒŒ์ž„๊ฒฐ๊ณผ : ํŒจ๋ฐฐ~" ๋ถ€๋ถ„์ด ๋‚˜์˜ค์ง€ ์•Š๋„๋ก ํ•  ๊ฒƒ
   *     >> ์กฐ๊ฑด๋ถ€ ๋ Œ๋”๋ง
   */

  let pos = ["์ขŒ", "์ •๋ฉด", "์šฐ"];

  const [myChoice, setMyChoice] = useState("");
  const [comChoice, setComChoice] = useState("");
  const [result, setResult] = useState("");

  //๋‚˜์˜ ์„ ํƒ์„ ์„ธํŒ…
  const handleChoice = (e) => {
    setMyChoice(e.target.innerText);

    //์ปดํ“จํ„ฐ ์„ ํƒ์„ ์„ธํŒ…
    let ran = parseInt(Math.random() * 3 + 1);
    setComChoice(pos[ran]);
  };

  useEffect(() => {
    //๊ฒŒ์ž„ ๊ฒฐ๊ณผ ํŒ๋ณ„
    myChoice == comChoice ? setResult("์Šน๋ฆฌ") : setResult("ํŒจ๋ฐฐ");
  }, [comChoice]);

  return (
    <div>
      <h1>์ฐธ์ฐธ์ฐธ ๊ฒŒ์ž„!</h1>
      <h3>๋‚˜์˜ ์„ ํƒ : {myChoice}</h3>
      <h3>์ปดํ“จํ„ฐ์˜ ์„ ํƒ : {comChoice}</h3>
      {myChoice && <h3>๊ฒŒ์ž„ ๊ฒฐ๊ณผ : {result}</h3>}

      {pos.map((item) => (
        <button key={item} onClick={handleChoice}>
          {item}
        </button>
      ))}
    </div>
  );
};

export default Ex03;

 

โš™๏ธ Q&A

 

const [myChoice, setMyChoice] = useState('')
{myChoice && <h3>๊ฒŒ์ž„๊ฒฐ๊ณผ : {result}</h3>}

 

myChoice ์˜ ์ดˆ๊ธฐ๊ฐ’์€ ๋นˆ๋ฌธ์ž์—ด

๋นˆ๋ฌธ์ž์—ด์ด๋ฉด false, ๋ฌธ์ž์—ด์ด๋ฉด true์ธ๊ฐ€?

 

JavaScript์—์„œ ๋ฌธ์ž์—ด ๋นˆ ๊ฐ’("")์„ ์ œ์™ธํ•œ ๋ชจ๋“  ๋ฌธ์ž์—ด์€ true๋กœ ๊ฐ„์ฃผํ•จ!