React的新手,我正在尝试在React中编写我的脚本但不知道该怎么做。我尝试过使用状态,但这让我更加困惑。下面的代码是我可能经常创建的一些示例。
这是我的剧本:
const hamburger = document.querySelector(".hamburger");
hamburger.addEventListener("click", function () {
hamburger.classList.toggle("is-active");
document.querySelector(".navigation").classList.toggle("slide-in");
document.querySelector("body").classList.toggle("menu-active");
document.querySelector(".shell-ui-main").classList.toggle("menu-overlay");
});
以下是导航栏的基本反应组件:
import React from 'react';
export default class NavComponent extends React.Component {
render() {
return (
<div className="container">
<button className="hamburger hamburger--squeeze" type="button">
<span className="hamburger-box">
<span className="hamburger-inner"></span>
</span>
</button>
<a className="logo-link" href="/">
<img width="94" height="31" src="/img/logos/logo.png" srcSet="/img/logos/logo.png 1x, /img/logos/logo@2x.png 2x, /img/logos/logo@3x.png 3x"
alt="logo" className="logo" />
</a>
<nav className="navigation">
<ul className="nav">
<li className="single-item">
<a href="/">Home</a>
</li>
<li className="single-item">
<a href="#">Item 2</a>
</li>
<li className="single-item">
<a href="#">Item 3</a>
</li>
<li className="single-item">
<a href="#">Item 4</a>
</li>
</ul>
</nav>
</div>
);
}
}
答案 0 :(得分:1)
如果有人有兴趣,这是解决方案。另外,我将道具向下传递给组件并从那里控制而不是单个const。
import React from 'react';
const HamburgerToggle = (props) => (
<button className={"hamburger hamburger--squeeze" + (props.active ? " is-active" : "")} onClick={props.clickHandler} type="button">
<span className="hamburger-box">
<span className="hamburger-inner"></span>
</span>
</button>
);
const Logo = () => (
<a className="logo-link" href="/">
<img width="94" height="31" src="/img/logos/logo.png" srcSet="/img/logos/logo.png 1x, /img/logos/logo@2x.png 2x, /img/logos/logo@3x.png 3x" alt="Logo" className="logo" />
</a>
);
const Navigation = (props) => (
<nav className={"navigation" + (props.active ? " slide-in" : "")}>
<ul className="nav">
<li className="single-item">
<a href="/">Home</a>
</li>
<li className="single-item">
<a href="#">intem 2</a>
</li>
<li className="single-item">
<a href="#">item 3</a>
</li>
<li className="single-item">
<a href="#">item 4</a>
</li>
</ul>
</nav>
);
export default class NavComponent extends React.Component {
state = {active: false};
handleClick(e){
this.setState({active: !this.state.active});
console.log(this.state.active);
}
render() {
return (
<div className="container">
<HamburgerToggle active={this.state.active} clickHandler={this.handleClick.bind(this)} />
<Logo />
<Navigation active={this.state.active} clickHandler={this.handleClick.bind(this)} />
</div>
);
}
}