我正在try 编写一个有两个按钮的简单计时器. 开始按钮:计时器将每10ms增加一个. 按下按钮:计时器将被推到一个数组中,并显示在前标签中. 不幸的是,Lap Button不起作用. 有人能帮我解决这个问题吗? 泰.
import { useState } from "react";
import { formatSeconds } from "./format";
let interval : NodeJS.Timer;
function App() {
const [buttonName, setButtonName] = useState("Start");
let [timer, setTimer] = useState(0);
const laps : Array<number> = [];
const handleStartClick = () => {
setButtonName(buttonName === "Start" ? "Stop" : "Start")
if(buttonName === "Start"){
interval = setInterval(() => {
setTimer(timer += 1)
}, 10);
}else{
clearInterval(interval)
}
}
const handleLapClick = () => {
laps.push(timer);
}
return (
<div>
<button onClick={handleStartClick}>{buttonName}</button>
<button onClick={handleLapClick}>Lap</button>
<div>
<p>Elapsed:</p> <pre id="elapsed">{formatSeconds(timer)}</pre>
</div>
<hr />
<div id="laps">
<p>Laps:</p>
{laps?.map((item) => {
return <pre key={item}>{formatSeconds(item)}</pre>;
})}
</div>
</div>
);
}
export default App;