问题
I have an absolutely positioned div:
class MyDiv extends React.Component {
state = {
stepCount: 0
};
componentDidMount(){
setInterval(() => {
this.setState({ stepCount: this.state.stepCount + 1 })
}, 1000);
}
render(){
return (<div style={{ left: this.state.stepCount * 10 + "%" }} />);
}
}
CSS
div { transition: 1s linear; }
Every second, I translate the div left by 10%. I want the transitions to look smooth, but there is a slight stutter.
Example: https://codepen.io/anon/pen/QoNGbQ
回答1:
Use css transforms instead of position for animations. It is more performant.
render(){
return (<div style={{ transform: `translateX(${this.state.step * 3 + "%"})`}} />);
}
See this article on medium
回答2:
You're probably best off using CSS transforms or a module such as react-spring, but if neither of them suit you then you want requestAnimationFrame
.
(CSS Transforms can make text blurry CSS transition effect makes image blurry / moves image 1px, in Chrome? and for a one-off you might not want the bundle load of an external module)
https://codesandbox.io/s/pj9m554nkj
const animate = ({ timing, draw, duration }) => {
let start = performance.now();
const animateLoop = time => {
const durationFraction = Math.min(
1,
Math.max(0, (time - start) / duration)
);
const progress = timing(durationFraction);
draw(progress);
if (durationFraction < 1) {
requestAnimationFrame(animateLoop);
}
};
requestAnimationFrame(animateLoop);
};
const MovingDiv = ({ move, duration }) => {
const [pos, setPos] = useState(0);
useEffect(() => {
animate({
timing: fraction => move * fraction,
draw: progress => setPos(progress),
duration
});
}, []);
return <div className="MovingDiv" style={{ left: pos }} />;
};
You can also then start playing with easeIn/easeOut in the timing function to add a bit of spring.. https://codesandbox.io/s/2w6ww8oymp
来源:https://stackoverflow.com/questions/54955894/smoothly-animate-a-div-as-its-position-changes