我为导航菜单制作了一个组件,点击后关闭并打开
class Panel extends Component {
openNav() {
// opens the navigation menu
// changes onClick attribute to closeNav()
}
closeNav() {
// closes the navigation menu
// changes onClick attribute to openNav()
}
render () {
return (
<div id="panel" className="hamburger"
onClick= {/*default value is openNav(),and when clicked,
changes to closeNav()*/} ></div>
);
}
}
有没有办法编写openNav()和closeNav(),以便在点击时可以一个接一个地重复调用它们? 另请告诉我们在render()中传递给onClick属性的内容。
答案 0 :(得分:0)
您可以调用您的函数“toggleNav”,然后执行以下操作:
onToggleNav() {
this.setState({
isNavbarOpen: !this.state.isNavbarOpen
});
}
render () {
return (
<div
id="panel"
className="hamburger"
onClick={::this.onToggleNav}
>
// I don't know if the div is your navbar or you have a specific navbar component. I just use the component below for demonstration purposes how to use the state then.
<Navbar
isOpened={this.state.isNavbarOpen}
/>
</div>
);
}
答案 1 :(得分:-1)
您可以使用状态变量this.state.open
来确定菜单是打开还是关闭:
class Panel extends Component {
constructor(props) {
super(props);
// You need to bind your functions in the constructor
this.openNav = this.openNav.bind(this);
this.closeNav = this.closeNav.bind(this);
this.onClick= this.onClick.bind(this);
}
openNav() {
this.setState({open: true});
}
closeNav() {
this.setState({open: false});
}
onClick() {
if (this.state.open) {
this.closeNav();
} else {
this.openNav();
}
}
render () {
return (
<div id="panel" className="hamburger"
onClick= {this.onClick} ></div>
);
}
}