reactjs - 几秒钟后隐藏 div ReactJS
问题描述
我试图在 ReactJS 上几秒钟后隐藏一个 div。到目前为止,这是我的代码:
setTimeout(function() {
$('#submitmsg').fadeOut('fast');
}, 3000);
<div id="submitmsg">
{message && <span> Messaged received. I'll respond to your query ASAP! </span> }
</div>
我收到一个错误,说“$”是未定义的。
解决方案
$
是 jquery
在反应中的标志,我们会说
document.getElementById('#submitmsg').fadeOut('fast');
我也将使用更简单的方法,将布尔值声明为 usestate
const Component = () =>{
const [showElement,setShowElement] = React.useState(true)
useEffect(()=>{
setTimeout(function() {
setShowElement(false)
}, 3000);
},
[])
return(
<div>
{showElement?<div>I'm here and i will be gone</div>:<></>}
</div>
)
}
更新:
在这里,我创建了一个代码沙盒示例这是整个代码,当我尝试它时它工作正常,正如您在上面的代码框中看到的那样
import React, { useEffect } from "react";
const MyComponent = () => {
const [showElement, setShowElement] = React.useState(true);
useEffect(() => {
setTimeout(function () {
setShowElement(false);
}, 10000);
}, []);
return (
<div>
<div>
{showElement ? (
<div
style={{
height: "100vh",
background: "black",
color: "white",
fontSize: "30px",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
fontFamily: "roboto",
opacity: showElement ? 1 : 0
}}
>
I'm here and i will be gone
</div>
) : (
<div></div>
)}{" "}
</div>
</div>
);
};
export default MyComponent;
https://codesandbox.io/s/thirsty-rosalind-o9pds?file=/src/App.js
推荐阅读
- python-3.x - 循环内的 Python PyQt5 组合框连接
- python-c-api - 如何正确地将 CuPy 数组发送到 Python C 扩展模块
- stripe-payments - 具有不同持续时间的产品的条带订阅
- npm - 如何从相对版本中获取确切的最新 npm 版本?
- .htaccess - .htaccess 如何重写要在 api-v2 文件上接收的 api/v2
- regex - Filebeat 将 mysql-slow.log 中的几行合并为一行
- python-3.x - 如何编写代码以打印出具有数百行的 .csv 列中数字的总和?
- c - C语言如何打开一个目录下的所有txt文件并统计一个单词出现的次数
- javascript - 尝试在 useEffect 挂钩中使用清理功能来清理 img.onload
- octobercms - 在 octobercms 中使用rainlab.user.activate 事件