gpt4 book ai didi

reactjs - 几秒钟后隐藏 div ReactJS

转载 作者:行者123 更新时间:2023-12-02 16:11:01 27 4
gpt4 key购买 nike

我试图在 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 的标志
在 react 中我们会说

  document.getElementById('#submitmsg').fadeOut('fast');

另外我会使用更简单的方法声明一个 bool 值是 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>
)
}

更新:

在这里我创建了一个 codesandbox 示例

这里是整个代码,当我尝试它时它工作正常,正如你在上面的 codesandbox 中看到的那样

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

关于reactjs - 几秒钟后隐藏 div ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68016644/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com