๐Ÿ“’TIL) React ์—ฌ๋Ÿฌ ์ธํ’‹ ํŽธํ•˜๊ฒŒ ๊ด€๋ฆฌํ•˜๊ธฐ

7213 ๋‹จ์–ด ReactReact

์—ฌ๋Ÿฌ ์ธํ’‹ ๊ด€๋ฆฌ๋ž€?

ํฐ ํ‹€๋กœ ๋ณด๊ฒŒ ๋˜๋ฉด ํšŒ์›๊ฐ€์ž… ํŽ˜์ด์ง€๋ผ๋˜๊ฐ€ ์˜ˆ์•ฝ ํ•˜๋Š” ํŽ˜์ด์ง€๋“ค์„ ๋ณด๊ฒŒ ๋˜๋ฉด ์ธํ’‹์ด๋‚˜ ํผ ์ฒ˜๋Ÿผ ๊ฐ’์„ ์ž…๋ ฅํ•˜๋Š” ์ฐฝ๋“ค์ด ์—„์ฒญ๋‚˜๊ฒŒ ๋งŽ์ด ์žˆ์Šต๋‹ˆ๋‹ค! ๊ทธ๋Ÿด๋•Œ ์ธํ’‹์„ ๊ด€๋ฆฌํ•˜๊ธฐ์— ์–ด๋–ค๊ฒŒ ์ฝ”๋“œ์ ์œผ๋กœ ํšจ์œจ์ ์ผ๊นŒ์— ๋Œ€ํ•ด ์–˜๊ธฐ๋ฅผ ํ•ด๋ณผ๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค!

State ๋ฅผ ํ•˜๋‚˜๋กœ!

๋ณดํ†ต ์•„๋ž˜์ฒ˜๋Ÿผ state๋ฅผ ์—ฌ๋Ÿฌ๊ฐœ๋ฅผ ์„ ์–ธํ•ด ๊ฐ’์„ ๊ด€๋ฆฌ๋ฅผ ํ•˜๊ฒŒ ๋ ๊ฒƒ์ด๋‹ค.

const [ id , setId] = useState('')
const [ pw , setPw] = useState('')
const [ email , setEmail] = useState('')

ํ•˜์ง€๋งŒ ์ธํ’‹์„ ๊ด€๋ฆฌํ•ด์•ผํ•  state๊ฐ€ ๋” ๋งŽ์•„์ง€๋ฉด ๋งŽ์•„์งˆ์ˆ˜๋ก ์ผ์ผํžˆ ์„ ์–ธ์„ ํ•ด์ค˜์•ผํ•˜๋Š” ๋ฒˆ๊ฑฐ๋กœ์›€์ด ์žˆ๋Š”๋ฐ
์ด๊ฑฐ๋ฅผ ํ•˜๋‚˜์˜ state์— ๊ฐ์ฒดํ˜•์œผ๋กœ ์ €์žฅ์ด ๊ฐ€๋Šฅํ•˜๋‹ค ์˜ˆ์‹œ๋Š” ์•„๋ž˜๋กœ!

const [inputs, setInputs] = useState({
  id: '',
  pw: '',
  email: '',
 });

์ด๋Ÿฐ์‹์œผ๋กœ inputs๋ผ๋Š” ์Šคํ…Œ์ดํŠธ ๊ฐ’์— ํ•˜๋‚˜๋กœ ๋‹ด์•„์„œ ๊ด€๋ฆฌ๋ฅด ํ• ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

ํ•จ์ˆ˜๋„ ํ•˜๋‚˜๋กœ??

๋ณดํ†ต ํ•จ์ˆ˜๋„ ์•„๋ž˜์ฒ˜๋Ÿผ ํ•˜๋‚˜์”ฉ ๋‹ค ์„ ์–ธ์„ ํ•ด์„œ ์‚ฌ์šฉํ–ˆ์„๊ฑฐ๋‹ค.

const handleId = e => {
  setId(e);
};

const handlePw = e => {
  setPw(e);
};
const handleEmail = e => {
  setEmail(e);
};

ํ•˜์ง€๋งŒ ์•„๋ž˜์ฒ˜๋Ÿผ name๊ณผ value๋ฅผ ์ด์šฉํ•ด ํ•˜๋‚˜์˜ ํ•จ์ˆ˜๋กœ ์—ฌ๋Ÿฌ state ๋ฅผ ์ปจํŠธ๋กค ๊ฐ€๋Šฅํ•˜๋‹ค!
์ปจํŠธ๋กค์„ ํ•˜๊ธฐ์œ„ํ•ด์„  ์ธํ’‹, ํผ ์—์„œ name ์ด๋ผ๋Š” ์†์„ฑ์„ ๋ถ€์—ฌํ•ด์ฃผ์–ด์•ผํ•œ๋‹ค.

<input type=text name=id onChange={handleInput}/>
<input type=text name=pw onChange={handleInput}/>
<input type=text name=email onChange={handleInput}/>
const handleInput = e => {
  const { value, name } = e.target;
  setInputs({
    ...inputs,
    [name]: value,
  });
};

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ