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과 Function의 차이가 궁금했는데 찾아봤더니(https://stackoverflow.com/questions/61293107/react-hooks-const-component-vs-functional-component) 코드 성능에는 별로 차이가 없는 것 같다.
// Const function
const Add = () => {
return();
}
// Function
function Add() {
return();
}
'프론트엔드 > React 공식문서 읽기' 카테고리의 다른 글
React로 사고하기 (0) | 2022.06.05 |
---|---|
합성 (Composition) vs 상속 (Inheritance) (0) | 2022.06.04 |
폼 (0) | 2022.06.02 |
리스트와 Key (0) | 2022.05.30 |
조건부 렌더링 (0) | 2022.05.28 |