anott 2022. 6. 3. 22:00
https://ko.reactjs.org/docs/lifting-state-up.html를 읽고 정리한 글입니다

 

  • 클래스형 컴포넌트로 작성된 코드를 함수형 컴포넌트로 바꿨다.

 

Calculator.jsx

import { useState } from "react";
import TemperatureInput from "./TemperatureInput";

function toCelsius(fahrenheit) {
  return ((fahrenheit - 32) * 5) / 9;
}

function toFahrenheit(celsius) {
  return (celsius * 9) / 5 + 32;
}

function tryConvert(temperature, convert) {
  const input = parseFloat(temperature);
  if (Number.isNaN(input)) {
    return "";
  }
  const output = convert(input);
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

function BoilingVerdict(props) {
  if (props.celsius >= 100) {
    return <p>The water would boil.</p>;
  }
  return <p>The water would not boil.</p>;
}

const Calculator = () => {
  const [scale, setScale] = useState("c");
  const [temperature, setTemperature] = useState("");
  const celsius =
    scale === "f" ? tryConvert(temperature, toCelsius) : temperature;
  const fahrenheit =
    scale === "c" ? tryConvert(temperature, toFahrenheit) : temperature;

  const handleCelsiusChange = (temperature) => {
    setScale("c");
    setTemperature(temperature);
  };

  const handleFahrenheitChange = (temperature) => {
    setScale("f");
    setTemperature(temperature);
  };

  return (
    <div>
      <TemperatureInput
        scale="c"
        temperature={celsius}
        onTemperatureChange={(temperature) => handleCelsiusChange(temperature)}
      />
      <TemperatureInput
        scale="f"
        temperature={fahrenheit}
        onTemperatureChange={(temperature) =>
          handleFahrenheitChange(temperature)
        }
      />
      <BoilingVerdict celsius={parseFloat(celsius)} />
    </div>
  );
};

export default Calculator;

 

TemperatureInput.jsx

const scaleNames = {
  c: "Celsius",
  f: "Fahrenheit",
};

const TemperatureInput = (props) => {
  const temperature = props.temperature;
  const scale = props.scale;

  const handleChange = (e) => {
    props.onTemperatureChange(e.target.value);
  };

  return (
    <fieldset>
      <legend>Enter temperature in {scaleNames[scale]}:</legend>
      <input value={temperature} onChange={(e) => handleChange(e)} />
    </fieldset>
  );
};

export default TemperatureInput;

 

  • useState의 초기화를 안 했더니 아래 에러가 났었다.
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component

 

// Const function
const Add = () => {
  return();
}

// Function
function Add() {
  return();
}