ReactJS/개념정리
[React] 시간변환기 완성하기
xowoony
2023. 3. 13. 13:01
학습일 : 2023. 03. 13
변동사항
setMinutes 를 -> setAmount 로 변경해주었다.
<!DOCTYPE html>
<html>
<body>
<!-- 리액트를 사용해서 태그를 생성할 것이기 때문에 body에 작성하지 않아도 됨. -->
<div id="root"></div>
</body>
<!-- 리액트 사용을 위한 스크립트 (필수로 적어줘야 함) -->
<!-- react-dom은 React element를 HTML에 두는 역할을 함. -->
<script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
<!-- Babel을 이용하여 코드를 변환 -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
function App() {
// state 생성
// array 의 첫번째 item 은 minutes 이며 이는 value 이다.
// array 의 두번째 item 은 setMinutes 이며 이는 value를 수정하고, component를 새로고침 할 때 쓰는 함수이다.
const [amount, setAmount] = React.useState(0);
const [inverted, setInverted] = React.useState(false); // default 값 = False
// onChange 함수 생성
const onChange = (event) => {
setAmount(event.target.value);
};
// 리셋 버튼 눌렀을 때 실행되는 함수 생성
const reset = () => {
setAmount(0);
};
// onFlip 함수 생성
// inverted가 true라면 false를 반환,
// false라면 true를 반환해주게 되는 함수이다.
const onInvert = () => {
// setinverted(!inverted);
// 위 보다는 아래 방법을 권장함
// 현재값을 받아서 그 반대값을 내놓는 함수이다.
reset();
setInverted((current) => !current);
};
return (
<div
style={{
height: "60vh",
color: "black",
alignItems: "center",
display: "flex",
flexDirection: "column",
justifyContent: "center",
}}
>
<h1 style={{ marginLeft: "2.5rem" }}>시간 변환기</h1>
<div style={{ marginBottom: "0.5rem" }}>
<label htmlFor="minutes" style={{ marginRight: "0.5rem" }}>
Minutes
</label>
<input
value={inverted ? amount * 60 : amount} // minutes 값이다. 이는 위 const [minutes, setMinutes] 즉 state에 있다.
id="minutes"
placeholder="Minutes"
type="number"
onChange={onChange}
disabled={inverted}
style={{ height: "2rem", width: "15rem" }}
/>
</div>
<div style={{ marginBottom: "1rem" }}>
<label htmlFor="hours" style={{ marginRight: "1.4rem" }}>
Hours
</label>
<input
// value 값 => 삼항연산자 사용
// 1. Hours input 태그가 disabled일 경우 Minutes 에 입력한 값 기반으로 시간으로 변환되어 결과값이 출력되게
// 2. Hours input태그가 활성화 되었을 경우엔 내가 입력한 값이 나오게
value={inverted ? amount : Math.round(amount / 60)} // Math.round() 는 소수점 이하를 반올림 하게 됨
id="hours"
placeholder="Hours"
type="number"
disabled={!inverted}
onChange={onChange}
style={{ height: "2rem", width: "15rem" }}
/>
</div>
{/*버튼*/}
<div>
<button
onClick={reset}
style={{
width: "6rem",
height: "2rem",
backgroundColor: "rgba(255, 255, 0, 0.14)",
border: "none",
marginRight: "2rem",
marginLeft: "3rem",
cursor: "pointer",
}}
>
리셋
</button>
<button
onClick={onInvert}
style={{
width: "6rem",
height: "2rem",
backgroundColor: "rgb(0 128 255 / 14%)",
border: "none",
cursor: "pointer",
}}
>
{inverted ? "돌아가기" : "자리 바꾸기"}
</button>
</div>
</div>
);
}
const root = document.getElementById("root");
ReactDOM.render(<App />, root);
</script>
</html>
간단하게 시간 변환기 만들기 끝!
리액트 안에서 아직 CSS 적용은 제대로 공부해보지 못해서
그냥 대충했음
이렇게 하는게 맞는지도 모르겠다.
실행결과는 아래와 같다.
끝~