온라인 강의/React 완벽 가이드 [Udemy]

58. State 대신 사용하기(그리고 더 나은 방법)

유호야 2023. 6. 2. 18:28
반응형

... 

const userInput = {
	name: 'Patrick', age: 23, gender: 'M'
};

const newUserInput = { ...userInput, age: 25 };

 

그리고 title과 amount, date가 바뀔 때마다 각가 함수를 만들어 업데이트할 수 있다

 ...userInput
< 이부분을 어떻게 업데이트 하는지가 문제가 될 수 있다 (왜..?)

 

ExpenseForm.js

import React, { useState } from "react";
import "./ExpenseForm.css";
const ExpenseForm = () => {
  const [enteredTitle, setEnteredTitle] = useState("");
  const [enteredAmount, setEnteredAmount] = useState("");
  const [enteredDate, setEnteredDate] = useState("");
  const [userInput, setUserInput] = useState({
    eneteredTitle: '',
    eneteredAmount: '',
    eneteredDate: '',
  })
  const titleChangeHandler = (event) => {
    setUserInput({
      ...userInput,
      enteredTitle: event.target.value
    })
  }

  const amountChangeHandler = (event) => {
    setUserInput({
      ...userInput,
      enteredAmount: event.target.value
    })
  }
  const dateChangeHandler = (event) => {
    setUserInput({
      ...userInput,
      enteredDate: event.target.value
    })
  }

  return <form>
    <div className="new-expense__controls">
      <div className="new-expense__control">
        <label htmlFor="">Title</label>
        <input type="text" onChange={titleChangeHandler} />
      </div>
      <div className="new-expense__control">
        <label htmlFor="">Amount</label>
        <input type="number" min="0.01" step="0.01 " onChange={amountChangeHandler} />
      </div>
      <div className="new-expense__control">
        <label htmlFor="">Date</label>
        <input type="date" min="2021-01-01" max="2023-12-31" onChange={dateChangeHandler} />
      </div>
      <div className="new-expense__actions">
        <button type="submit">Add Expense</button>
      </div>
    </div>
  </form>
}

export default ExpenseForm;
반응형