我开始学习 React 框架,但实际上我正在从主站点查看此代码,但仍然无法理解
tick: function() {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentDidMount: function() {
this.interval = setInterval(this.tick, 1000);
如果我传递this.tick
给setInterval
,那么当计时器事件在引擎盖下被触发this.tick
并被调用时,它可能应该在window
对象的上下文中被调用,对吧?如果这是真的,那么tick
函数中的代码应该是错误的,因为对象上没有setState
函数window
。
var Timer = React.createClass({
getInitialState: function() {
return {secondsElapsed: 0};
},
tick: function() {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentDidMount: function() {
this.interval = setInterval(this.tick, 1000);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
render: function() {
return React.DOM.div({},
'Seconds Elapsed: ', this.state.secondsElapsed
);
}
});
React.renderComponent(Timer({}), mountNode);