[英]how to remove a usestate element from the dom after 30 seconds in react js
我想在 30 秒后从 dom 中删除一个 usestate 元素有没有办法做到这一点:
let [showComponent, setShowComponent] = useState(false);
const handleClick = () => setShowComponent(!showComponent);
这是我的组件:
<div role="button" className="user-navigation--item" onClick={toggleLogoutMessage}>
<i className="fas fa-sign-out-alt user--nav--icon"></i>
{' Logout '}
{showComponent && <h1>Do you really want to log out</h1>} // remove this element after 30 sec
</div>
尝试使用 setTimeout 来延迟您的 function:
setTimeout(function() { your_func(); }, 30000);
let [showComponent, setShowComponent] = useState(false);
const handleClick = () => {
setTimeout(function() { setShowComponent(prev => !prev ); }, 30000);
}
是的,这是可以做到的。 以下是一个简化的示例,它最初将show
state 设置为true
,但随后还会启动setTimeout
,在 30 秒后将其设置回false
。
function Component() {
const [show, setShow] = useState(false);
const showMessage = () => {
setShow(true);
setTimeout(() => {
setShow(false);
}, 30000);
}
return (
<>
<button onClick={showMessage}>Logout</button>
{show && "Are you sure?"}
</>
);
}
let [showComponent, setShowComponent] = useState(false);
const handleClick = () => setTimeout(function() { setShowComponent(!showComponent); }, 30000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.