reactjs - ReactJS TypeError:无法读取未定义的属性“toggleShow”
问题描述
我是 React.js 的新手,我做错了得到这个错误消息。我试图弄清楚如何创建一个菜单按钮组件,当您每次单击汉堡时,该组件会在移动设备上向下滑动。
这是一条错误消息TypeError: Cannot read property 'toggleShow' of undefined:
18 | toggleShow() {
19 | this.toggleShow = this.toggleShow.bind(this)
| ^ 20 | this.hide = this.hide.bind(this)
21 | this.setState({ show: !this.state.show });
22 | }
我的完整反应代码:
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
});
}
推荐阅读
- azure - 当 ADF 发布分支受 git 保护时如何发布?
- c++ - 为什么在传递共享 ptr 对象时收到 c26486 警告
- rstudio - 在 RStudio 文件窗格中获取选定文件的文件路径
- java - 如何在 spring-boot 过滤器中获取自定义注释
- php - 如何在 else 语句之后到达 $fileName 变量的范围?
- c# - 如何在 Realm.Net 中设置“忽略”/仅运行时的 RealmObject 成员?
- python - 配置不当:“sql_server.pyodbc”在 CentOS7 中不是可用的数据库后端
- sql - 从 3m 返回数据,或下一个可用日期
- java - 哪个相当于 Java 的“isinstance”(Python)?
- python - Anaconda Gstreamer Gst packge 缺少“jpegenc”