【问题标题】:Smoothly animate a div as its position changes随着位置的变化平滑地为 div 设置动画
【发布时间】:2019-07-24 03:37:47
【问题描述】:

我有一个绝对定位的 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; }

每一秒,我将 div 左移 10%。 我希望过渡看起来平滑,但有轻微的口吃。

示例: https://codepen.io/anon/pen/QoNGbQ

【问题讨论】:

  • react 有几个动画库,如果你打算在几个地方做不同类型的动画,使用一个库比做 manul css-transitions 更好。以react-spring 为例。

标签: reactjs css-transitions


【解决方案1】:

对动画使用 css 变换而不是位置。它的性能更高。

  render(){
    return (<div style={{ transform: `translateX(${this.state.step * 3 + "%"})`}} />);
  }

this媒体上的文章

【讨论】:

    【解决方案2】:

    您可能最好使用 CSS 转换或 react-spring 等模块,但如果它们都不适合您,那么您需要 requestAnimationFrame

    (CSS 转换可以使文本模糊 CSS transition effect makes image blurry / moves image 1px, in Chrome? 并且一次性您可能不希望外部模块的捆绑加载)

    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 }} />;
    };
    

    你也可以开始在计时功能中使用easeIn/easeOut来增加一点弹簧..https://codesandbox.io/s/2w6ww8oymp

    【讨论】:

      猜你喜欢
      • 2012-12-03
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 2014-01-31
      相关资源
      最近更新 更多