forked from EFUB/efub4-first-react-study
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Calculator.jsx
53 lines (50 loc) Β· 1.59 KB
/
Calculator.jsx
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
44
45
46
47
48
49
50
51
52
53
import React,{useState}from "react";
import TemperatureInput from "./TemperatureInput";
function BoilingVerdict(props){
if(props.celsius>=100){
return <p>λ¬Όμ΄ λμ΅λλ€.</p>;
}
return <p>λ¬Όμ΄ λμ§ μμ΅λλ€.</p>;
}
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 calculator(props){
const[temperature,setTemperature]=useState("");
const[scale,setScale]=useState("c");
const handleCelsiusChange=(temperature)=>{
setTemperature(temperature);
setScale("c");
};
const handleFahrenheitChange=(temperature)=>{
setTemperature(temperature);
setScale("f");
};
const celsius=scale==="f"?tryConvert(temperature,toCelsius):temperature;
const fahrenheit=scale==="c"?tryConvert(temperature,toFahrenheit):temperature;
return(<div>
<TemperatureInput
scale="c"
temperature={celsius}
onTemperatureChange={handleCelsiusChange}
></TemperatureInput>
<TemperatureInput
scale="f"
temperature={fahrenheit}
onTemperatureChange={handleFahrenheitChange}
></TemperatureInput>
<BoilingVerdict celsius={parseFloat(celsius)}></BoilingVerdict>
</div>)
}