[React] Controlled Component

Hannahhhยท2022๋…„ 8์›” 2์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
10/30

๐Ÿ” Controlled Component

์•„๋ž˜์˜ ํŠธ์œ— ์ „์†ก ํผ์„ ์˜ˆ๋กœ ๋“ค๋ฉด,

์œ„ ๊ทธ๋ฆผ์„ ํ•˜์˜ ํŠธ์œ— ์ „์†ก ํผ ์ปดํฌ๋„ŒํŠธ๋ผ๊ณ  ํ–ˆ์„ ๋•Œ, state๋Š” username(๋ณด๋‚ด๋Š” ์‚ฌ๋žŒ)๊ณผ tweet(๋‚ด์šฉ)์ด ๋œ๋‹ค.

React์—์„œ๋Š” ์ƒํƒœ์— ํ•ด๋‹นํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ state๋กœ ๋”ฐ๋กœ ๊ด€๋ฆฌํ•˜๊ณ  ์‹ถ์–ดํ•˜๋ฉฐ, React๊ฐ€ state๋ฅผ ํ†ต์ œํ•  ์ˆ˜ ์žˆ๋Š” ์ปดํฌ๋„ŒํŠธ๋ฅผ Contorlled Component๋ผ๊ณ  ํ•œ๋‹ค.


React๊ฐ€ state๋ฅผ ํ†ต์ œํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š”, input์— ๊ฐ’์ด ๋ณ€๊ฒฝํ•จ์— ๋”ฐ๋ผ, state๋„ ์‹ค์‹œ๊ฐ„์œผ๋กœ ๋ฐ”๋€Œ๋ฉด๋œ๋‹ค.(onChange)



Controlled Component ์˜ˆ์‹œ


์•„๋ž˜๋Š” React Controlled Coponent๋ฅผ ๊ตฌํ˜„ํ•œ ์ฝ”๋“œ์ด๋‹ค.

export default function App() {
  const [username, setUsername] = useState("");
  const [msg, setMsg] = useState("");

  return (
    <div className="App">
      <div>{username}</div>
      <input
        type="text"
        value={username}
        onChange={(event) => setUsername(event.target.value)}
        placeholder="์—ฌ๊ธฐ๋Š” ์ธํ’‹์ž…๋‹ˆ๋‹ค."
        className="tweetForm__input--username"
      ></input>
      <div>{msg}</div>
      {/* TODO : ์œ„ input๊ณผ ๊ฐ™์ด ์ž…๋ ฅ์— ๋”ฐ๋ผ์„œ msg state๊ฐ€ ๋ณ€ํ•  ์ˆ˜ ์žˆ๊ฒŒ 
      ์•„๋ž˜ textarea๋ฅผ ๋ณ€๊ฒฝํ•˜์„ธ์š”. */}
      <textarea
        placeholder="์—ฌ๊ธฐ๋Š” ํ…์ŠคํŠธ ์˜์—ญ์ž…๋‹ˆ๋‹ค."
        className="tweetForm__input--message"
        onChange={(event) => {setMsg(event.target.value)}}
        value={msg}
      ></textarea>
    </div>
  );
}




Reference: ์ฝ”๋“œ์Šคํ…Œ์ด์ธ 

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