我试图在固定的时间内在屏幕上移动文本,为此我想出了以下代码
import React, { Component, useState, useEffect, useRef } from "react";
import { PrismCode } from "react-prism";
import { Player, ControlBar } from "video-react";
import { Button } from "reactstrap";
import { getSub_Millis } from "../../services/srtreader";
export default function Rythmoband(props) {
const initialPosition = useRef(
props.rythmoPosition === undefined ? "30%" : props.rythmoPosition
);
const [number, setnumber] = useState(
props.dialogueNumber === undefined ? 0 : props.dialogueNumber
);
const [timerCheck, setTimerCheck] = useState(true);
const [moverNumber, setMoverNumber] = useState(0.001);
const [currentTime, setCurrentTime] = useState(0);
const textMover = () => {
let x = parseFloat(initialPosition.current);
let start = getSub_Millis(props.time[number][0]);
let end = getSub_Millis(props.time[number][1]);
let timeToMove = start - end;
setMoverNumber((timeToMove / 2500) * props.player.playbackRate);
setCurrentTime(props.time.currentTime);
x = x + moverNumber;
let y = `${x}%`;
initialPosition.current = y;
};
setTimeout(() => {
textMover();
timercheck();
backChecker();
}, 0.1);
const timercheck = () => {
if (
getSub_Millis(props.time[number][1]) - props.player.currentTime * 1000 <
1
) {
initialPosition.current = "30%";
setnumber(number + 1);
}
};
const backChecker = () => {
for (let index = 0; index < props.time.length; index++) {
if (
getSub_Millis(props.time[index][1]) > props.player.currentTime * 1000 &&
getSub_Millis(props.time[index][0]) < props.player.currentTime * 1000
) {
setnumber(index);
}
}
};
return (
<>
<div
style={{
width: window.innerWidth,
background: "#FF8232",
marginTop: "20px",
height: "75px",
position: "relative",
border: "5px solid black",
}}
>
<div
style={{
width: "5px",
background: "red",
marginTop: "20px",
height: "75px",
position: "absolute",
top: "-25%",
left: "25%",
}}
></div>
<strong
style={{
position: "absolute",
left: initialPosition.current,
top: "25%",
fontSize: "2rem",
}}
>
{props.dialogue[number]}
</strong>
</div>
</>
);
}
在上面的代码中,setTimeout负责在设定的时间后重复调用相同的函数,从而以计算的方式在屏幕上移动文本。现在的问题是,文本元素的移动是块状的,而不是平滑的,尽管我也尝试过改变时间间隔和移动速度。如果有人能帮我想出一个更好的方法让文本更流畅,我将不胜感激。
- 为了性能,避免每次都更新状态
- setTimeout接受毫秒,这意味着0.1毫秒对性能来说非常困难,可能是0.1秒
- React上有很多动画包,这一个非常机械
- 解决方案:使用css转换