react -- 计时器

var SetIntervalMixin = {
componentWillMount: function(){
this.intervals = [];
},
setInterval: function(){
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function(){
this.intervals.forEach(clearInterval);
}
};

var TickTock = React.createClass({
mixins: [SetIntervalMixin],
getInitialState: function(){
return { seconds: 0 }
},
componentDidMount: function(){
this.setInterval(this.tick, 1000);
},
tick: function(){
this.setState({ seconds: this.state.seconds + 1 });
},
render: function(){
return (
<p>React has been running for {this.state.seconds} seconds.</p>
);
}
});

ReactDOM.render(
<TickTock />,
document.querySelector('.demo')
);

posted @ 2016-04-28 00:49  以神之名  阅读(961)  评论(0编辑  收藏  举报