React.js: Non-CSS animations

前端 未结 4 708
暗喜
暗喜 2021-02-07 04:20

React documentation doesn’t have anything about handling animations that are not CSS transitions, such as animation of scroll position and SVG attributes.

As for CSS tra

4条回答
  •  爱一瞬间的悲伤
    2021-02-07 04:35

    This is what I came up so far: http://jsfiddle.net/NV/NtP7n/.

    I rewrote Dot to leverage React’s draw loop:

    var Dot = React.createClass({
    
        getInitialState: function() {
            return {
                start: 0,
                x: 0,
                final: 0,
                startTime: 0
            };
        },
    
        render: function() {
            var state = this.state;
            var props = this.props;
            var amount = 0;
    
            if (state.final !== props.x) {
                state.final = props.x;
                state.start = state.x;
                state.startTime = Date.now();
            } else {
                amount = (Date.now() - state.startTime) / this.props.duration;
            }
    
            if (amount <= 1) {
                var x = state.start + amount * (props.x - state.start);
                setTimeout(function() {
                    this.setState({x: x});
                }.bind(this), 1);
            } else {
                state.final = state.x = x = props.x;
            }
    
            return 
        }
    });
    

    I have to call:

    setTimeout(function() {
        this.setState({current: x});
    }.bind(this), 1);
    

    just to force update on the next tick. I have to use setTimeout because setState isn’t allowed in render method. I wonder if I can queue an update on the next tick without using setTimeout.

提交回复
热议问题