[英]Implementing a Drawer & AppBar with Material-UI + React {Cannot read property 'open' of null}
So I'm trying to use React
& Material-UI
to create an app, so I managed to get the AppBar up and running but am having some issues getting the Drawer to work. 所以我试图使用
React
& Material-UI
创建一个应用程序,所以我设法使AppBar启动并运行,但是在使Drawer正常工作时遇到了一些问题。
I keep getting an error: cannot read property open of null
, and have tried to figure out what the issue is to with no success. 我不断收到
error: cannot read property open of null
,并试图找出问题所在,但没有成功。 I found a 2 post on Stack about this exact issue, both of them don't have an answer that was able to resolve my problem 我在Stack上发现了2个关于此确切问题的帖子,但他们两个都没有能够解决我的问题的答案
Having trouble using Appbar + Drawer (Material UI + ReactJS) 使用Appbar +抽屉(材料UI + ReactJS)时遇到问题
What is Uncaught TypeError: Cannot read property 'open' of undefined for AppBar + Drawer component (ReactJS + Material-UI)? 什么是未捕获的TypeError:无法读取AppBar + Drawer组件(ReactJS + Material-UI)的未定义属性'open'?
This is my current code: 这是我当前的代码:
constructor() { super(); this.handleToggle = this.handleToggle.bind(this) this.handleClose = this.handleClose.bind(this) this.setState = { open: false }; } handleToggle = () => this.setState({open: !this.state.open}); handleClose = () => this.setState({open: false}); render() { return <MuiThemeProvider muiTheme={getMuiTheme()}> <AppBar onLeftIconButtonTouchTap={this.handleToggle} onLeftIconButtonClick={this.handleToggle} title="How long have you been alive?" iconClassNameRight="muidocs-icon-navigation-expand-more" /> <Drawer docked={false} width={200} open={this.state.open} onRequestChange={(open) => this.setState({open})} > <MenuItem onTouchTap={this.handleClose}>Menu Item 1</MenuItem> <MenuItem onTouchTap={this.handleClose}>Menu Item 2</MenuItem> </Drawer> </MuiThemeProvider> }
(snippit isn't suppose to run, just show my relevant code) (snippit不能运行,只显示我的相关代码)
I thought maybe binding this
to render
would help, but it did not :( 我认为也许
this
绑定到render
会有所帮助,但它没有:(
Problem in your code is you are not setting state in constructor. 代码中的问题是您没有在构造函数中设置状态。
this.setState
in constructor is wrong, it needs to be replaced with this.state
构造函数中的
this.setState
错误,需要用this.state
替换
constructor() {
super();
//...other lines of codes that you may intend to write
this.state = {
open: false
};
}
this.setState()
is a method that you call to update component's state from any method of a Component-Class except render()
and constructor()
this.setState()
是一种方法,您可以从Component-Class的任何方法(除render()
和constructor()
之外render()
更新组件的状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.