范围内的onPress()
函数,你可能想要把setInterval()
方法。你可以试试下面的代码:
var SetIntervalMixin = {
componentWillMount: function() {
this.intervals = [];
},
setInterval: function() {
this.intervals.map(clearInterval);
this.intervals.push(setInterval.apply(null, arguments));
}
};
var App = React.createClass({
mixins: [SetIntervalMixin], // Use the mixin
getInitialState: function() {
return {
seconds: 0,
nClicks: 0
};
},
onPress: function(plus) {
//this.setState({nClicks: plus});
this.setInterval(this.codeToExcecute, plus * 1000); // Call a method on the mixin
this.setState({nClicks: this.state.nClicks + 1});
},
codeToExcecute: function() {
console.log('Im the code to excecute');
},
render: function() {
return (
<div>
<p>
React has been running for {this.state.seconds} seconds. nClick: { this.state.nClicks }
</p>
<button onClick={ this.onPress.bind(null, this.state.nClicks + 1) }>Click</button>
</div>
);
}
});
React.render(
<App />,
document.getElementById('example')
);
演示:http://jsbin.com/biyibu/2/edit
这不是我清楚你想要做什么。 – FakeRainBrigand