本文介绍了ReactJS:css转换不在componentDidMount中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当装载 EffectBox 组件时,我想添加 show class 到这个组件。但css过渡不起作用。

When the EffectBox component is mounted, I want to add a show class to this component. But css transition doesn't work.

这是js代码:

 var EffectBox = React.createClass({
   componentDidMount: function () {
     this.show();
     // setTimeout(this.show, 100);
    },

    show: function () {
      $(React.findDOMNode(this)).addClass('show');
    },

    render: function () {
      return (
        <div className="effect-box" >
        <div className="header"></div>
        <div className="content">
        ...
       )
    }
  });

Css如下:

.effect-box {
  transform: translate3d(0, -100%, 0);
  transition: all .4s;
}

.show {
  transform: none;
}

当我使用延迟时调用show 函数(使用setTimeout),css动画可以正常工作。此时(componentDidMount),真正的DOM是否已呈现?

And when I use a delay to call show function(use setTimeout), the css animation works. At this point (componentDidMount), did the real DOM get rendered?

推荐答案


我更喜欢的是包装 this.show() requestAnimationFrame (这是轻微的超时版本。)

I've met this problem and I've found a couple solutions:
One that I prefer more is to wrap this.show() in requestAnimationFrame (It's gently version of timeout.)

componentDidMount: function () {
     requestAnimationFrame(()=> {this.show();});
 }

第二个非常粗鲁,但如果你不想使用任何一种超时你可以触发重新布局。它可能会损害应用程序性能。

Second one is very rude but if you don't want to use any kind of timeout you can trigger relayout. It may harm application performance.

componentDidMount: function () {
  document.body.offsetHeight;
  this.show();
}

这篇关于ReactJS:css转换不在componentDidMount中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 11:08