리액트에서 버튼을 추가해 변수값을 변경시키는 방법을 배웠다.
jsx를 이용한다.
import { useState } from "react";
function App() {
const [time, setTime] = useState(1) // 이걸 쓰면 자동으로 import가 됩니다.
// 타임을 변경시킬 수 있는 것 setTime
const handleClick = () =>
setTime(time +1);
console.log('업데이트')
return (
<div>
<span> 현재 시간: {time}시 </span>
<button onClick={handleClick}>시각 변경</button>
</div>
);
}
export default App;

이렇게 하면 계속 숫자가 올라간다. 17시 22시 39시 끝까지 올라갈 것이다.
이를 상용시로 바꾸는 식을 추가해주자.
import { useState } from "react";
function App() {
const [time, setTime] = useState(1) // 이걸 쓰면 자동으로 import가 됩니다.
// 타임을 변경시킬 수 있는 것 setTime
const handleClick = () => {
let newTime;
if(time >=12) {
newTime = 1; // time+1 > 13
} else {
newTime = time + 1;
}
setTime(newTime)
}
console.log('업데이트')
return (
<div>
<span> 현재 시간: {time}시 </span>
<button onClick={handleClick}>시각 변경</button>
</div>
);
}
export default App;
