javascript - 使用 Material-UI + React 实现抽屉和 AppBar {无法读取 null 的属性 'open'}

标签 javascript reactjs ecmascript-6 material-ui

所以我尝试使用 ReactMaterial-UI 创建一个应用程序,所以我设法让 AppBar 启动并运行,但遇到一些问题抽屉工作。

我不断收到错误:无法读取 null 的属性打开,并且尝试找出问题所在,但没有成功。我在 Stack 上找到了关于这个确切问题的 2 篇帖子,它们都没有能够解决我的问题的答案

Having trouble using Appbar + Drawer (Material UI + ReactJS)

What is Uncaught TypeError: Cannot read property 'open' of undefined for AppBar + Drawer component (ReactJS + Material-UI)?

这是我当前的代码:

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/

相关文章:

javascript - 如何使用 jQuery 检查图像 url 是否已加载?

javascript - 如何将 $PATH 设置为通过 node-pty 在 Node 中生成进程的一部分?

javascript - 如何在 react 中将json推送到Mobx的数组状态

javascript - React/Jest setUp 测试以定义 windows 对象

reactjs - React 中的 HTML 和 ES6 模板文字

Node.js - 服务器不是构造函数() ES6

javascript - 尝试隐藏我的 API key 会破坏我的 URL。有人知道为什么吗?

javascript - 将属性传输到组件的简单方法

javascript - 使用带有参数的重新选择选择器

javascript - 如何从同一个表单元素中逃脱 Jquery 表单验证?