我正在尝试做一个具有固定超时的加载栏,表示在 5 秒内,加载栏应该全部填满。我能够编写 html 和 css,但卡在 js 逻辑中。
function App() {
const [tick, setTick] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setTick(tick => tick + 10); //some calculation is missing
}, 1000);
setTimeout(() => {
clearInterval(id);
}, 5000);
return () => clearInterval(id);
}, []);
return (
<div className="App">
<div
style={{
width: "100%",
background: "yellow",
border: "1px solid"
}}
>
<div
style={{
height: "10px",
background: "black",
width: tick + "%"
}}
/>
</div>
</div>
);
}
最佳答案
我稍微重构了你的代码。
我创建了 3 个常量:
- maxLoad:是要覆盖的百分比,在您的情况下为 100%。
- fulfillInterval:填充栏中的一个步骤的时间间隔。
- step:计算填充当前迭代的宽度。
然后我更改了一段代码,在clearTimeout 中添加了 1 毫秒,以确保它能够正常工作并且......它正在工作。 :)
希望这有帮助。
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [tick, setTick] = useState(0);
const maxLoad = 100; // total percentage to cover
const fulfillInterval = 5000; // clear interval timeout
const step = maxLoad/(fulfillInterval/1000); // % filled every step
useEffect(() => {
const id = setInterval(() => {
setTick(tick => tick + step); // No dependency anymore
}, 1000);
setTimeout(() => {
clearInterval(id);
}, fulfillInterval+1);
return () => clearInterval(id);
}, []);
return (
<div className="App">
<div
style={{
width: "100%",
background: "yellow",
border: "1px solid"
}}
>
<div
style={{
height: "10px",
background: "black",
width: tick + "%"
}}
/>
</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
关于javascript - 用增量值和超时填充栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59282158/