我是React.js的新手,为了得到此错误消息,我做错了。我试图弄清楚如何创建一个菜单按钮组件,当您每次单击汉堡包时,该按钮组件都会在移动设备上向下滑动。
这是一条错误消息TypeError:无法读取未定义的属性'toggleShow':
18 | toggleShow() {
19 | this.toggleShow = this.toggleShow.bind(this)
| ^ 20 | this.hide = this.hide.bind(this)
21 | this.setState({ show: !this.state.show });
22 | }
我的完整React代码:
import React from 'react';
import { BrowserRouter as Router, Link } from 'react-router-dom';
import Dropdown from "../components/pages/dropdowns/dropdown.js";
import hamburger from "../components/images/menu.svg";
class Navigation extends React.Component {
constructor(props) {
super(props);
this.state = {
show: false
}
}
toggleShow() {
this.toggleShow = this.toggleShow.bind(this)
this.hide = this.hide.bind(this)
this.setState({ show: !this.state.show });
}
hide(e) {
if (e && e.relatedTarget) {
e.relatedTarget.click();
}
this.setState({ show: false });
}
render() {
return (
<Router>
<div className="FlexContainer NavbarContainer">
<div className="mobilecontainer LeftNav">
<h2 className="BrandName LeftNav mobileboxmenu inline FarRight">Kommonplaces</h2>
<div
className="hamburger inlinev"
onClick={this.toggleShow}
onBlur={this.hide}>
<img alt="menubtn" src={hamburger}></img>
</div>
</div>
{
this.state.show &&
(
<ul className="NavBar">
<Dropdown/>
<li className="RightNav"><Link to="/">Host Your Space</Link></li>
<li className="RightNav"><Link to="/">About Us</Link></li>
<li className="RightNav"><Link to0="/">Contact Us</Link></li>
<li className="RightNav"><Link to="/">Sign Up</Link></li>
<li className="RightNav"><Link to="/">Login</Link></li>
</ul>
)
}
</div>
</Router>
);
}
}
export default Navigation;
您需要在构造函数内部移动bind
语句
constructor(props) {
super(props);
this.state = {
show: false
}
this.toggleShow = this.toggleShow.bind(this)
this.hide = this.hide.bind(this)
}
toggleShow() {
this.setState({
show: !this.state.show
});
}