我是 React 中的功能组件的新手,想知道如何将下面的代码从基于功能的代码转换为基于类的代码。我已经尝试过了,但我在“React.useEffect”方面遇到了麻烦。
任何帮助将不胜感激!:)
(还有一个问题,你会说我学习基于类的功能组件更好吗?)
代码
import { Component } from "react";
import "./App.css";
import React from "react";
import audio from "./250629__kwahmah-02__alarm1.mp3";
import UIfx from "uifx";
import { render } from "@testing-library/react";
function Timer() {
const [time, setTime] = React.useState(0);
const [timerOn, setTimeOn] = React.useState(false);
React.useEffect(() => {
let interval = null;
if (timerOn) {
interval = setInterval(() => {
setTime((prevTime) => prevTime + 1); // We wanna increase the time every 10 milliseconds
}, 1000);
} else {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [timerOn]);
return (
<div className="App">
<header className="App-header">
{/* <div>{time}</div> */}
<div>
<h1>
{("0" + parseInt(time / 3600)).slice(-2)}:
{("0" + parseInt((time / 60) % 60)).slice(-2)}:
{("0" + parseInt(time % 60)).slice(-2)}
</h1>
</div>
<div>
{!timerOn && time === 0 && (
<button id="StartTimer" onClick={() => setTimeOn(true)}>
Start
</button>
)}
{timerOn && (
<button id="PauseTimer" onClick={() => setTimeOn(false)}>
Pause
</button>
)}
{!timerOn && time !== 0 && (
<button id="ResumeTimer" onClick={() => setTimeOn(true)}>
Resume
</button>
)}
{!timerOn && time > 0 && (
<button id="ResetTimer" onClick={() => setTime(0)}>
Reset
</button>
)}
</div>
</header>
</div>
);
}
export default Timer;