我正在尝试制作一个汉堡包菜单,单击“我想要移动查看汉堡包”下拉菜单(从display:flex转到display:initial)。看来我不能让js工作了。。
我对JavaScript还不太熟悉,有人能解释一下遗漏了什么吗?
从函数Nav返回和导出并在App.js中呈现的html:
<div class="Navbar__Link Navbar__Link-brand">
<NavLink to="/" exact>
<img className="logo" src="https://i.imgur.com/KnEvuRJ.png"></img>
</NavLink>
</div>
<div class="Navbar__Link Navbar__Link-toggle">
<i class="fa fa-bars"></i>
</div>
<nav class="Navbar__Items">
<div class="Navbar__Link">
<NavLink className="nav-link" to="/" exact activeClassName="active">
Home
</NavLink>
</div>
<div class="Navbar__Link">
<NavLink className="nav-link" to="/about" activeClassName="active">
About
</NavLink>
</div>
<div class="Navbar__Link">
<NavLink className="nav-link" to="/chars" activeClassName="active">
Characters
</NavLink>
</div>
<div class="Navbar__Link">
<NavLink className="nav-link" to="/login" activeClassName="active">
Login
</NavLink>
</div>
</nav>
</div>
要切换的js代码:
function classToggle() {
const navs = document.querySelectorAll('.Navbar__Items')
navs.forEach(nav => nav.classList.toggle('Navbar__ToggleShow'));
}
document.querySelector('.Navbar__Link-toggle')
.addEventListener('click', classToggle);
css:(在@media..中)
.Navbar__Link-toggle {
align-self: flex-end;
display: initial;
position: absolute;
cursor: pointer;
}
TypeError:无法读取null的属性“addEventListener”
最佳答案
这不是React
的工作方式,这里绝对不需要使用vanilla js。用state
的属性绑定类切换行为怎么样?
class Component extends React.Component{
state = {
isButtonToggled: false
}
handleClick = () => this.setState({isButtonToggled : !this.state.isButtonToggled})
render(){
const { isButtonToggled } = this.state
const buttonStyle = classnames({
['button-root'] : true,
['button-toggled'] : isButtonToggled
})
return(
<button onClick={this.handleClick} className={buttonStyle}>Click</button>
)
}
}
关于javascript - 如何在单击时更改元素的className? (汉堡菜单),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57208958/