var MyComponent = React.createClass({
getDefaultProps:function () {
return {
position:100,
time:10
}
},
getInitialState:function () {
return {position:0}
},
render:function () {
var style={
color:'red',
marginLeft:this.state.position
}
return <div style={style}>动画</div>
},
tranformComponent:function () {
if(this.state.position < this.props.position) {
this.setState({
position:++this.state.position
})
console.log(this.state.position);
}else {
clearInterval(this.timer)
}
},
componentDidMount:function () {
this.timer = setInterval(this.tranformComponent,this.props.time);
}
})
ReactDOM.render(<MyComponent position={200}/>, document.getElementById("mydiv"));
核心思想是用定时器不断的改变state状态,不断的调用render重绘,从而不断改变组件的margin值来实现。