这是您可以实现的。如果不查看更多代码,您将很难准确地提供您想要的。
首先,这是一个发出事件的简单动画函数。您可以使用这些事件从动画代码与 React UI 代码进行通信。
function animate(from, to, duration) {
const events = {};
// Basic event emitter, used to communicate from this function to React
const emitter = {
on(event, fn) {
if (!events.hasOwnProperty(event)) {
events[event] = [];
}
events[event].push(fn);
let index = events.length - 1;
return () => events[event].splice(index, 1);
},
emit(event, data) {
(events[event] || []).forEach((fn) => fn(data));
},
};
const startTime = Date.now();
const map = (n, x1, y1, x2, y2) => Math.min(Math.max(((n - x1) * (y2 - x2)) / (y1 - x1) + x2, x2), y2);
let frame;
(function update() {
frame = requestAnimationFrame(update);
const delta = Date.now() - startTime;
const value = map(delta, 0, duration, from, to);
emitter.emit("tick", value);
})();
return emitter;
}
以下是在 React 中实现此功能的方法。
function Task(props) {
const [complete, setComplete] = useState(false);
useEffect(() => {
if (!complete) {
return;
}
// Start the animation when this task is complete
const animation = animate(0, 100, 2000);
const tickListener = animation.on("tick", (value) => {
// Animation has updated, do something with the value
console.log(value);
});
const endListener = animation.on("end", () => {
// Animation has now ended, do something else.
console.log("Animation ended.");
});
// Remove events
return () => {
tickListener();
endListener();
};
}, [complete]);
return null; // Render UI
}
这将在任务标记为completed 时启动动画,并在动画值更改时触发tick(使用它来更新某些内容)。动画结束后,它将发出end,您可以使用它来执行任何附加代码,例如反转动画。