我试图在React中触发此CSS打开,但本教程使用的是HTML,但我无法使用addeventlistner或document.queryselector,因此我向汉堡包添加了一个onClick事件,该事件现在应该处理这两个问题,我只需要切换即可此类别。请不要将其标记为已回答,因为回答的问题与jquery和常规html相关。
组件:
const Navbar = props => {
const hamburger = document.querySelector('.hamburger');
const navLinks = document.querySelector('.nav-links');
const links = document.querySelectorAll('nav-links li');
// hamburger.addEventListener('click', () => {
// navLinks.classList.toggle("open")
// });
useEffect(() => {
}, []);
return (
<div>
<nav>
<div onCLick={//I want to toggle the open class on click} className="hamburger">
<div className="line"></div>
<div className="line"></div>
<div className="line"></div>
</div>
<ul className="nav-links">
<li className="nav-links">About</li>
<li className="nav-links">About</li>
<li className="nav-links">About</li>
</ul>
</nav>
</div>
);
};
export default Navbar;
CSS:
nav{
height: 10vh;
background: blue !important;
}
.nav-links{
display: flex;
list-style: none;
width: 50%;
height: 100%;
justify-content: space-around;
align-items: center;
margin-left: auto;
}
/* change to classes */
.nav-links li a{
color: white;
text-decoration: none;
font-size: 16px
}
.landing{
height: 90vh;
display: flex;
justify-content: center;
align-items: center;
}
.landing h1{
margin: 100px;
font-size: 50px;
}
@media screen and (max-width: 768px){
.nav-links{
position: fixed;
background: red;
height: 100vh;
width: 100%;
flex-direction: column;
display: none;
clip-path: circle(100px at 90% 10%);
-webkit-clip-path: circle(100px at 90% 10%);
z-index: 99999;
transition: all 1s ease-out
}
.nav-links.open{
clip-path: circle(1000px at 90% 10%);
-webkit-clip-path: circle(1000px at 90% 10%);
}
.line{
width: 30px;
height: 3px;
background: white;
margin: 5px
}
nav{
position: relative
}
.hamburger{
position: absolute;
cursor: pointer;
right: 5%;
top: 50%;
transform: translate(-5%,-50%)
}
}
答案 0 :(得分:1)
您应该使用state
,这是React用来帮助您跟踪组件当前状态的方法(就像单击汉堡包一样)。 React背后的核心概念之一是为JSX定义事件监听器。因此,当用户与您的应用程序进行交互时,会触发一个事件,从而使组件的state
发生变化。
我们使用state
帮助您构建所需的功能。在这种情况下,单击汉堡包将切换open state
,因此我们使用该state
布尔值来帮助我们切换导航链接列表的类别。
您无需像使用普通JavaScript中的典型文档选择器那样与DOM
进行强制交互。
查看有效的沙箱:https://codesandbox.io/s/cool-wildflower-94e6q
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const Navbar = props => {
const [open, setOpen] = useState(false);
return (
<div>
<nav>
<div onClick={() => setOpen(!open)} className="hamburger">
<div className="line" />
<div className="line" />
<div className="line" />
</div>
<ul className={open ? "nav-links" : "hide"}>
<li className="nav-links">About</li>
<li className="nav-links">About</li>
<li className="nav-links">About</li>
</ul>
</nav>
</div>
);
};
export default Navbar;
const rootElement = document.getElementById("root");
ReactDOM.render(<Navbar />, rootElement);