search

Home  >  Q&A  >  body text

react js模拟动画疑问

var AnimationExample=React.createClass({

            getInitialState:function(){
                return {
                    position:0
                }
            },
            animationFun:function(){
                if(this.state.position<this.props.position){
                    this.setState({
                        position:this.state.position+1
                    })
                }
            },
            componentDidUpdate:function(){
                if(this.props.position){
                    setTimeout(this.animationFun,this.props.timeoutMs)
                }
            },
            render:function(){
                var divStl={
                    marginLeft:this.state.position
                };
                return (
                    <div style={divStl}>This is animate!</div>
                )
            }
            
        });
        

        ReactDOM.render(
            <AnimationExample />,
            document.getElementById('animationContent')
        );
        ReactDOM.render(
            <AnimationExample position={100} timeoutMs={10}/>,document.getElementById('animationContent')
        );

这是一个简单的js模拟动画,我的疑问是为什么最后要render两次,而render一次不行呢

高洛峰高洛峰2938 days ago723

reply all(1)I'll reply

  • 三叔

    三叔2016-11-15 16:43:13

    因为列出的component会根据position属性的变化而更新,第一次render时compoent没有props.position,第二次render后props.position的值为100。

    reply
    0
  • Cancelreply