所以我尝试使用 React
和 Material-UI
创建一个应用程序,所以我设法让 AppBar 启动并运行,但遇到一些问题抽屉工作。
我不断收到错误:无法读取 null 的属性打开
,并且尝试找出问题所在,但没有成功。我在 Stack 上找到了关于这个确切问题的 2 篇帖子,它们都没有能够解决我的问题的答案
Having trouble using Appbar + Drawer (Material UI + ReactJS)
这是我当前的代码:
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 不应该运行,只是显示我的相关代码)
我认为也许将 this
绑定(bind)到 render
会有帮助,但事实并非如此:(
最佳答案
代码中的问题是您没有在构造函数中设置状态。构造函数中的this.setState
错误,需要替换为this.state
constructor() {
super();
//...other lines of codes that you may intend to write
this.state = {
open: false
};
}
this.setState()
是一个方法,您可以通过组件类的任何方法(render()
和 constructor( 除外)调用该方法来更新组件的状态。 )
关于javascript - 使用 Material-UI + React 实现抽屉和 AppBar {无法读取 null 的属性 'open'},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38939634/