新的react 钩子和状态,试图找出我的代码不工作的原因.
我有一个App.js
文件和一个名为Menu.js
的子组件.基本上,Menu.js
包含一个菜单,如果变量isOpen
是true
,我想显示它,如果变量isOpen
是false
,我想隐藏它.我在App.js
上添加了父级功能,因为我还有另一个组件需要能够更新isOpen
的状态,但该组件与我的问题无关.以下是相关代码:
App.js:
import Menu from "./components/Menu";
import { useState } from "react";
export default function App() {
const [isOpen, setIsOpen] = useState(false);
const toggleState = () => setIsOpen(!isOpen);
console.log(isOpen);
// This will console log either true or false
const menuBtn = document.querySelector(".hamburgermenu");
const mobileMenu = document.querySelector(".mobilemenu");
// These are elements on the child component, Menu.js
if (isOpen) {
menuBtn.classList.add("open");
mobileMenu.style.zIndex = "5";
// This should reveal the menu if the value of isOpen is true
} else {
menuBtn.classList.remove("open");
mobileMenu.style.zIndex = "0";
// This should hide the menu if the value of isOpen is false
}
return (
<div>
<Menu togglestate={toggleState} />
// Passing togglestate down to Menu.js as a prop
</div>
);
}
Menu.js:
export default function Menu(props) {
return (
<div>
<div className="hamburgermenu" onClick={props.togglestate}>Stuff in here</div>
// Clicking this div will toggle the value of isOpen between true and false
<div className="mobilemenu">Stuff in here</div>
</div>
);
}
当我试图运行它时,我的整个应用程序都中断了,我在menuBtn.classList.remove("open");
处得到了错误TypeError: Cannot read properties of null (reading 'classList')
我知道我的问题在于默认状态是false
,所以它将首先try 运行else
语句.然而,由于类open
还没有添加到menuBtn
元素中,因此没有要删除的open
类,它正在出错.
我试图在原来的else
语句中添加另一个嵌套的if/else
语句,基本上是说if元素有一个名为open
的类,删除它,如下所示:
if (isOpen) {
menuBtn.classList.add("open");
mobileMenu.style.zIndex = "5";
} else {
if (menuBtn.classList.contains("open")) {
menuBtn.classList.remove("open");
mobileMenu.style.zIndex = "0";
} else {
mobileMenu.style.zIndex = "0";
}
}
我还try 完全脱离类,直接更改样式作为测试,如下所示:
if (menuOpen) {
menuBtn.style.display = "block";
mobileMenu.style.zIndex = "5";
} else {
menuBtn.style.display = "none";
mobileMenu.style.zIndex = "0";
}
但我在同一行有个错误,在menuBtn.style.display = "block";
行有个错误
我知道这有点乱.我相信有更好的方法可以做到这一点,但我会用我所掌握的知识来做这件事.如果有更简单的方法,我愿意接受建议!