All files / src/chap04 StateForm.js

0% Statements 0/6
100% Branches 0/0
0% Functions 0/3
0% Lines 0/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                                                                                     
import { useState } from 'react';
 
export default function StateForm() {
  // 폼으로 취급하는 값을 State로 선언
  const [form, setForm] = useState({
    name: '홍길동',
    age: 18
  });
 
  // 폼 요소의 변경 사항을 State에 반영
  const handleForm = e => {
    setForm({
      ...form,
      [e.target.name]: e.target.value
    });
  };
  
  // [보내기] 버튼으로 로그에 메시지 출력하기
  const show = () => {
    console.log(`안녕하세요, ${form.name}(${form.age}세) 님!`);
  };
 
  return (
    <form>
      {/* 개별 폼 요소에 State 값 할당 */}
      <div>
        <label htmlFor="name">이름: </label>
        <input id="name" name="name" type="text"
          onChange={handleForm} value={form.name} />
      </div>
      <div>
        <label htmlFor="age">나이:</label>
        <input id="age" name="age" type="number"
          onChange={handleForm} value={form.age} />
      </div>
      <div>
        <button type="button" onClick={show}>
          보내기</button>
      </div>
      <p>안녕하세요, {form.name}({form.age}세) 님!</p>
    </form>
  );
}