英文:
Uncaught TypeError: Cannot read properties of undefined (reading 'add') | React js
问题
我是新手编程,正在尝试制作一个“页面未找到”的页面,但我遇到了以下错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'add')
如何解决这个问题?
这是代码:
setTimeout(function () {
const notFoundElement = document.getElementsByClassName(
"not-found-animation"
);
notFoundElement.classNameList.add("hinge-falling");
console.log("setTimeout Loaded...");
}, 2200);
<h1 className="not-found-animation">404</h1>
英文:
Im new to coding and Im trying to make a "page not found" page but im getting the following error
Uncaught TypeError: Cannot read properties of undefined (reading 'add')
How can I solve this problem?
Here is the code:
setTimeout(function () {
const notFoundElement = document.getElementsByClassName(
"not-found-animation"
);
notFoundElement.classNameList.add("hinge-falling");
console.log("setTimeout Loaded...");
}, 2200);
<h1 className="not-found-animation">404</h1>
答案1
得分: 1
以下是您要翻译的内容:
不要在React中使用原始DOM(不良实践)。
解决方案
- 使用useState Hook
const [toggle, setToggle] = useState(false);
setTimeout(function () {
setToggle(!toggle);
console.log("setTimeout Loaded...");
}, 2200);
<h1 className={`${toggle && "not-found-animation"}`}>404</h1>;
- 使用useRef Hook
const ref = useRef(null);
setTimeout(function () {
const h1 = ref.current; // 相应的DOM节点
h1.className = "not-found-animation";
console.log("setTimeout Loaded...");
}, 2200);
<h1 ref={ref}>404</h1>;
英文:
Don't use the original DOM in React (bad practice).
solutions
- Using useState Hook
const [toggle, setToggle] = useState(false);
setTimeout(function () {
setToggle(!toggle);
console.log("setTimeout Loaded...");
}, 2200);
<h1 className={`${toggle && "not-found-animation"}`}>404</h1>;
- Using useRef Hook
const ref = useRef(null);
setTimeout(function () {
const h1 = ref.current; // corresponding DOM node
h1.className = "not-found-animation";
console.log("setTimeout Loaded...");
}, 2200);
<h1 ref={ref}>404</h1>;
答案2
得分: -1
你需要使用 [0] 访问集合中的第一个元素,
尝试:
setTimeout(function () {
const notFoundElement = document.getElementsByClassName(
"not-found-animation"
);
notFoundElement[0].classList.add("hinge-falling");
console.log("setTimeout Loaded...");
}, 2200);
英文:
you need to access the first element in the collection using [0],
Try:
setTimeout(function () {
const notFoundElement = document.getElementsByClassName(
"not-found-animation"
);
notFoundElement[0].classList.add("hinge-falling");
console.log("setTimeout Loaded...");
}, 2200);
答案3
得分: -1
尝试这个:notFoundElement.setAttribute('class', 'hinge-falling')
英文:
try this notFoundElement.setAttribute('class','hinge-falling')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论