我是Reactjs
的新手,在使用setTimeOut
时我遇到了阻止它的最佳方法。我应该使用clearTimeOut
还是stopPropagation()
。
这是我的代码
render: function() {
return ( < div className = "colorClick"
style = {
{
background: this.state.bgColor
}
}
onClick = {
this.detectColor
} > < /div><br/ >
);
},
calcTime: function() {
var time = Math.floor((Math.random() * 9) + 1);
this.setState({
total_time: time
}, () => {
window.setTimeout(this.calcTime, 250)
});
},
detectColor: function(event) {
window.clearTimeout(this.state.total_time);
window.clearTimeout(this.calcTime);
},
componentDidMount: function() {
this.calcTime();
},
componentWillUnmount: function() {
this.detectColor();
}
在此代码中,我使用的是clearTimeOut
,但它无法使用。我希望当我点击div
className="colorClick"
时,setimeOut应该清除并重置。
答案 0 :(得分:4)
您错误地使用了clearTimeout
。您需要将window.setTimeout
的结果存储在变量中,然后使用该变量作为参数调用window.clearTimeout
。以下是w3schools的示例,其中显示了这一点。
答案 1 :(得分:0)
您的代码中存在一些不良做法。我会在代码中评论这些变化。另外,我猜你使用的是React.createClass
,不推荐使用。
请改用类语法。和Horia说的一样,你需要将超时存储在一个变量中,所以整个代码看起来像这样:
import React from 'react'
class MyComponent extends React.Component {
// notice no ":" and no "function"
render () {
return (
<div {/* no space between "<" and the div */}
className="colorClick" {/* no space around "=" */}
style={ { background: this.state.bgColor } } {/* no space around "=" */}
onClick={ this.clearTimeout } {/* no space around "=" */}
/> {/* div is self closing, use this when there's no childs */}
);
} // no ","
calcTime () {
// use const if variable is not reassigned
const time = Math.floor((Math.random() * 9) + 1);
this.setState({
total_time: time
}, () => {
// assign timeout to component property
this.timeout = window.setTimeout(this.calcTime, 250)
});
}
// no "event" passed as an argument since its:
// 1. unnecessary
// 2. doesn't exit when called in componentWillUnmount
// method name changed to clearTimeout since it's more accurately describe what it does
// notice fat arrow syntax to bind clearTimeout context to the class
clearTimeout = () => {
// use clearTimeout on the stored timeout in the class property "timeout"
window.clearTimeout(this.timeout);
}
componentDidMount () {
this.calcTime();
}
componentWillUnmount () {
this.clearTimeout();
}
}