所以我有很多解决方案的网站,每个人都是一些包,但我不需要任何包,它应该只使用Reactjs <div className="odometer-value">100</div>
中的纯js
所以我有很多解决方案的网站,每个人都是一些包,但我不需要任何包,它应该只使用Reactjs <div className="odometer-value">100</div>
中的纯js
有许多库默认为它提供了很酷的可视化表示,但正如您所说的,您正在寻找简单的实现,所以我在几分钟内就写了一些东西.
Assuming you are not looking for fancy animations and just a counter counting up/down on value change is fine,下面的代码应该适用于您.
import { useEffect, useState } from "react";
import "./SpeedoMeter.css";
export default function SpeedoMeter({ value }) {
// Current shown value
const [currentValue, setCurrentValue] = useState(0);
// Target Value to reach
const [targetValue, setTargetValue] = useState(0);
// Number of step to reach
const steps = 10;
// Latency between each step, if this is 0 then the count up/down is very instant and wont work
const lag = 1;
// Updating target value
useEffect(() => {
setTargetValue(value);
}, [value]);
// Updating Current value to follow target value, a feedback loop if made so that useEffect depencency can be leveraged.
// Note: This is not super accurate in timing/animations
useEffect(() => {
if (currentValue !== targetValue) {
setTimeout(() => {
setCurrentValue((prevCurr) => {
let distance = Math.abs(targetValue - currentValue);
let stepSize = Math.ceil(distance / steps);
return currentValue < targetValue
? currentValue + stepSize
: currentValue - stepSize;
});
}, lag);
}
}, [currentValue, targetValue]);
return (
<div className="speedo-wrap">
{(currentValue + "").split("").map((val, idx) => (
<div className="speedo-digit" style={{ marginTop: `-${val}em` }}>
<div data-val="0">0</div>
<div data-val="1">1</div>
<div data-val="2">2</div>
<div data-val="3">3</div>
<div data-val="4">4</div>
<div data-val="5">5</div>
<div data-val="6">6</div>
<div data-val="7">7</div>
<div data-val="8">8</div>
<div data-val="9">9</div>
</div>
))}
</div>
);
}
CSS个
.speedo-wrap {
display: flex;
justify-content: center;
height: 1rem;
font-size: 1rem;
line-height: 1rem;
overflow: hidden;
}
.speedo-digit {
transition: 1s all;
}
USAGE个
<SpeedoMeter value={10000} />
Adding CodeSandbox for same:https://codesandbox.io/s/basic-react-speedometer-gsv5yc?file=/src/SpeedoMeter.js
此外,立方贝塞尔可以很容易地控制动画,数字的视觉表示也可以改变,副作用最小,速度/步数可以控制.