最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React element width animation - Stack Overflow

programmeradmin0浏览0评论

In my React based application I'm trying to perform a simple css3 width transition like:

.foo {
    transition: width 1s ease-in-out;
}

what I want to do is set a style inside an element in the react ponent which is "width: xx%" and the animate it from 0% to xx%. Since the element when rendered already has this property the animation is not working. I've looked into the "ReactCSSTransitionGroup" but did not e closer to a solution. I started messing around with setTimeOut to set the style attribute after the ponent was rendered but it felt really messy and "hackish". Could someone point me in the right direction?

In my React based application I'm trying to perform a simple css3 width transition like:

.foo {
    transition: width 1s ease-in-out;
}

what I want to do is set a style inside an element in the react ponent which is "width: xx%" and the animate it from 0% to xx%. Since the element when rendered already has this property the animation is not working. I've looked into the "ReactCSSTransitionGroup" but did not e closer to a solution. I started messing around with setTimeOut to set the style attribute after the ponent was rendered but it felt really messy and "hackish". Could someone point me in the right direction?

Share Improve this question asked Mar 30, 2017 at 18:01 martenolofssonmartenolofsson 5311 gold badge5 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

If you are trying to animate the ponent after it has been rendered (from 0 to n%) you can do it by calling setState in ponentDidMount. As browsers are not rerendering stuff that has changed in the same animation frame but merge changes and render the end result, you'll need to wrap it in requestAnimationFrame

I explained it throughly in this blog post.

Code will look like this:

export default class AnimateMe extends Component {
  state = {
    width: 0
  };

  ponentDidMount() {
    requestAnimationFrame(() => {
      this.setState({ width: "75%" });
    });
  }

  render() {
    return (
      <div style={{ width: this.state.width }}>
        Animate my width
      </div>
    );
  }
}

I made a working example: https://codesandbox.io/s/7z1j794oy1

Hope that helps!

发布评论

评论列表(0)

  1. 暂无评论