我试图在5秒后执行一个函数,但它在渲染后立即执行
下面是我的代码class App extends React.Component {
onInactive = (ms, cb) => {
var wait = setTimeout(cb, ms);
document.onmousemove = document.mousedown = document.mouseup = document.onkeydown = document.onkeyup = document.focus = function () {
clearTimeout(wait);
wait = setTimeout(cb, ms);
};
};
render() {
this.onInactive(5000, alert("Inactive for 5 seconds"));
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}
export default App;
这是我的codesandbox链接
在您的代码中,第二个参数不是一个函数,它是一个语句,但是setTimeout函数期望第一个参数是一个回调函数。请查看下面的工作代码。
import React from "react";
/**
* Add any other events listeners here
*/
// const events = ["mousemove", "click", "keypress"];
class App extends React.Component {
onInactive = (ms, cb) => {
var wait = setTimeout(cb, ms);
document.onmousemove = document.mousedown = document.mouseup = document.onkeydown = document.onkeyup = document.focus = function () {
clearTimeout(wait);
wait = setTimeout(cb, ms);
};
};
render() {
this.onInactive(5000, () => alert("Inactive for 5 seconds"));
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}
export default App;