[소플의 처음 만난 리액트] 12장 실습문제

이 포스트에서는 컴포넌트를 효율적으로 사용하고, 공유 상태를 통해 부모 컴포넌트의 상태를 자식 컴포넌트에서 공유할 수 있으며, 소수점 자릿수를 반올림하는 방법을 정리했습니다.
Jan 02, 2024
[소플의 처음 만난 리액트] 12장 실습문제

TemperatureInput.jsx

import React from "react"; // 온도를 입력받기 위한 컴포넌트 const scaleNames = { c: '섭씨', f: '화씨', a: '절대온도' }; function TemperatureInput(props){ const {scale, temperature, onTemperatureChange} = props return ( <fieldset> <legend>온도를 입력해주세요(단위: {scaleNames[scale]}):</legend> <input value={temperature} onChange={onTemperatureChange} /> </fieldset> ) } export default TemperatureInput;

BoilingVerdict.jsx

import React from "react"; // 물의 끓음 여부를 알려주는 컴포넌트 function BoilingVerdict(props){ if (props.celsius >=100){ return <p>물이 끓습니다.</p> } return <p>물이 끓지 않습니다.</p> } export default BoilingVerdict;

Calculator.jsx

import React, { useState } from "react"; import BoilingVerdict from "./BoilingVerdict"; import TemperatureInput from "./TemperatureInput"; // 온도 변환 함수 function fahrenheitToCelsius(fahrenheit) { return (fahrenheit - 32) * 5 / 9; } function celsiusToFahrenheit(celsius) { return (celsius * 9 / 5) + 32; } function celsiusToAbsolute(celsius) { return (celsius + 273); } function fahrenheitToAbsolute(fahrenheit) { return (fahrenheit - 32) * 5 / 9 + 273 } function AbsoluteToCelsius(absolute) { return (absolute - 273); } function AbsoluteToFahrenheit(absolute) { return ((absolute - 273) * 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(); } // state가 하나이므로 자식요소의 영향이 부모까지 미친다. function Calculator(props) { const [temperature, setTemperature] = useState(''); const [scale, setScale] = useState('c'); const handleCelsiusChange = (event) => { setTemperature(event.target.value); setScale('c'); } const handleFahrenheitChange = (event) => { setTemperature(event.target.value); setScale('f'); } const handleAbsoluteChange = (event) => { setTemperature(event.target.value); setScale('a'); } const celsius = scale !== 'c' ? (scale === 'f' ? tryConvert(temperature, fahrenheitToCelsius) : tryConvert(temperature, AbsoluteToCelsius)) : temperature; const fahrenheit = scale !== 'f' ? (scale === 'c' ? tryConvert(temperature, celsiusToFahrenheit) : tryConvert(temperature, AbsoluteToFahrenheit)) : temperature; const absolute = scale !== 'a' ? (scale === 'c' ? tryConvert(temperature, celsiusToAbsolute) : tryConvert(temperature, fahrenheitToAbsolute)) : temperature; return ( <div> <TemperatureInput scale="c" temperature={celsius} onTemperatureChange={handleCelsiusChange} /> <TemperatureInput scale="f" temperature={fahrenheit} onTemperatureChange={handleFahrenheitChange} /> <TemperatureInput scale="a" temperature={absolute} onTemperatureChange={handleAbsoluteChange} /> <BoilingVerdict celsius={celsius} /> </div> ) } export default Calculator;

핵심 키워드

  • 컴포넌트 내에서 공통적으로 사용되는 부분을 추출하여 컴포넌트를 효율적으로 사용할 수 있다.
  • shared state를 통해 부모 컴포넌트의 state를 자식 컴포넌트들도 공유해서 사용이 가능하다.
  • 소수점 자리수를 반올림 하기 위해서는 원하는 자릿수만큼 곱한 후, Math.round() 함수를 통해 반올림을 진행한 다음, 곱했던 자릿수만큼 다시 나누는 과정을 거친다.
 

결론!

공통적으로 사용하는 state를 활용하여 코드를 효율적으로 작성하는 방법에 대해 알 수 있었다.
Share article
RSSPowered by inblog