์ง๋ ๊ฒ์๊ธ์์ ์ซ์ ์ ๋ ฅํ ๋ ์๋์ผ๋ก ์๊ฐ ๊ตฌ๋ถ (":") ํด์ฃผ๋๊ฑฐ๋ ์ํฐํค ์ ๋ ฅ์ผ๋ก + ๊ตฌํ์ ํ๋ค.
๊ทผ๋ฐ ๋ด๊ฐ ์ํ๋ ๊ฒ์ ๊ทผ๋ฌด ์๊ฐ์ ์ ๋ถ ๋ํด์ผํ๊ธฐ ๋๋ฌธ์,
๋ํ ๊ฒ์ ๋ ๋ํ๊ณ ๋ ๋ํ๊ณ ๋ ๋ํ๋ ์ด๋ฐ~ ๊ณ์ฐ๊ธฐ ๊ฐ์ ๊ธฐ๋ฅ์ด ํ์ํ๋ค.
์๊ฐ ๋์ ํด์ ๋ํ๊ธฐ
const result = `${adjustedHours
.toString()
.padStart(2, "0")}:${adjustedMinutes.toString().padStart(2, "0")}`;
setState({
time1: result,
time2: "",
result: "",
});
๊ฒฐ๊ณผ๊ฐ์ (๋ง์ ์ ํ ํ) result ๋ฅผ time1์ ๋ฃ์ด์ค๋ค.
๊ทธ๋ฆฌ๊ณ ์๋ time2 ์ ์ด๊ธฐ๊ฐ์ด 00:00 ์ด์๋๋ฐ ์ด๊ฒ๋ ๋น ๋ฌธ์์ด๋ก ๋ฐ๊พธ์ด์ฃผ์๋ค.
00:00์ผ๋ก ํ๋๋ ์ ๋ ฅ์ด ๋ฐ๋ก ์๋์ด์ ๋ถํธํ์.
์ด๋ ๊ฒ ๋ฐ๊ฟ์ฃผ์๋๋ ๋ฐ๋ก๋ฐ๋ก ๋์ ํด์ ๋ํ๊ธฐ๊ฐ ์ฝ๊ฒ ๊ฐ๋ฅํด์ก๋ค.
๋ ์๋ฆฌ๋ง ์ ๋ ฅํ์ ๋ ์๋์ผ๋ก :00 ์ ๋ถ์ฌ ์๊ฐ์ด ๋๊ฒ ํ๊ธฐ
์๋ฅผ ๋ค์ด 15๋ง ์ ๋ ฅํ๋ฉด, ์๋ ํํ๊ฐ **:**๊ฐ ์๋๋ผ์ ์/๋ถ์ผ๋ก ๋๋ ์ง์ง๊ฐ ์์
๊ฒฐ๊ณผ๊ฐ์ด NaN:NaN์ด ๋์จ๋ค.
์ฒ์์๋ ์ํฐ๋ฅผ ์ณค์๋, ํด๋น input ๊ฐ์ ๊ธธ์ด๊ฐ 2์ผ๋ ๋ค์ ์๋์ผ๋ก :00์ ๋ถ์ด๊ฒ ํ๋ ค๊ณ ํ๋ค.
๊ทธ๋์ handleInputKeyPressํจ์๋ฅผ ๊ณ์ ์์ ํด๋ดค๋๋ฐ ๋๋ฌด์ง ์๋ผ์ ใ ใ
์ ๋ ฅ์ ๋ณ์ ์์ฒด๋ฅผ ์์ ํ๋ค.
const handleAdd = () => {
const t1 = state.time1.includes(":")
? state.time1.split(":")
: [state.time1, "00"];
const t2 = state.time2.includes(":")
? state.time2.split(":")
: [state.time2, "00"];
const hours = parseInt(t1[0]) + parseInt(t2[0]);
const minutes = parseInt(t1[1]) + parseInt(t2[1]);
const toHours = Math.floor(minutes / 60);
const adjHours = hours + toHours;
const adjMinutes = minutes % 60;
const result = `${adjHours.toString().padStart(2, "0")}:${adjMinutes
.toString()
.padStart(2, "0")}`;
setState({
time1: result,
time2: "",
result: "",
});
};
ํ๋ฉด์ ์ฒ์ ์ง์ ํ์ ๋ ์๋์ผ๋ก input์ผ๋ก
const inputRef = useRef<HTMLInputElement>(null);
..
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
์ด์ input ref ์์ฑ์ inputRef๋ฅผ ์ถ๊ฐํด์ฃผ๋ฉด ๋๋ค.
๊ณ์ฐ ๊ธฐ๋ก ๋์ดํ๊ธฐ
์ด์ ๋์ ํด์ ๋ํ๋๋ฐ, ์๋ชป๋ํ์ ์๋ ์์ผ๋๊น
๊ณ์ฐ์ ์ด๋ป๊ฒ ํ๋์ง ๋ณผ ์ ์๋ history ์ฐฝ์ด ํ์ํ๊ฒ ๋ค ์ถ์์!
const [history, setHistory] = useState<string[]>([]);
setHistory([
...history,
`${state.time1} + ${state.time2} = ${adjHours}์๊ฐ ${adjMinutes}๋ถ`,
]);
๊ทธ๋ฆฌ๊ณ ์ด์ Add ํจ์๊ฐ ์คํ๋ ๋ history์ ํด๋น ์ ๋ณด๋ค์ ๋ด์์ค๋ค.
const handleClear = () => {
setState({
...state,
time1: "",
time2: "",
result: "",
});
setHistory([]);
};
clear ๋ฒํผ์ ๋๋ ์ ๋ history ์ฐฝ๋ ๋น์์ฃผ๊ณ ,
<div className="history-container">
<h3>HISTORY</h3>
<ul>
{history.map((calculation, index) => (
<li key={index}>{calculation}</li>
))}
</ul>
</div>
๊ทธ๋ฆฌ๊ณ div์ ๋ฃ์ด์ฃผ๊ณ css ์ข ๋ค๋ฌ์ด ์ฃผ๋ฉด ์์ฑ!
์ด๊ฑฐ ์ด๋ ๊ฒ ๋๊ณ ๋ณด๋๊น, ๋ฐ์ ๊ฐ์ด ์ถ๊ฐ๋ ๋ ์คํฌ๋กค์ด ์๋์ผ๋ก ์ ๋ด๋ ค๊ฐ๋๊ฒ ๊ฑฐ์ฌ๋ ธ๋ค..
๊ณ์ฐ ๊ธฐ๋ก ์ถ๊ฐ๋ ๋๋ง๋ค ์คํฌ๋กค ์๋๋ก ๋ด๋ฆฌ๊ธฐ
const historyRef = useRef<HTMLDivElement>(null);
...
// handleAdd ํจ์์ ์ถ๊ฐ
if (historyRef.current) {
historyRef.current.scrollTop = historyRef.current.scrollHeight;
}
...
<div className="history-container" ref={historyRef}>
์ด์ ๊ณ์ฐ์์ด ์ถ๊ฐ๋จ์ ๋ฐ๋ผ ํญ์ ๊ฐ์ฅ ํ๋จ์ ํ๋ฉด์ด ์์นํ๊ฒ ๋์๋ค