【问题标题】:Implementing a Drawer & AppBar with Material-UI + React {Cannot read property 'open' of null}使用 Material-UI + React 实现 Drawer & AppBar {Cannot read property 'open' of null}
【发布时间】:2016-12-20 17:55:41
【问题描述】:

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

我不断收到error: cannot read property open of 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 绑定到render 可能会有所帮助,但它没有:(

【问题讨论】:

  • this.render = this.render.bind(this) 删除这个并添加this.handleToggle = this. handleToggle.bind(this) 和构造方法中的其他函数相同
  • 所以我之前尝试过,但仍然遇到同样的错误(现在再试一次,仍然没有)。似乎错误来自open={this.state.open}。不知道是什么导致它失败。

标签: javascript reactjs ecmascript-6 material-ui


【解决方案1】:

您的代码中的问题是您没有在构造函数中设置状态。构造函数中的this.setState错误,需要替换为this.state

constructor() {
    super();
    //...other lines of codes that you may intend to write

    this.state = {
      open: false
    };

  }

this.setState() 是一种方法,您可以调用该方法从 Component-Class 的任何方法(render()constructor() 除外)更新组件的状态

【讨论】:

  • 我编辑了上面的代码,向您展示了我目前拥有的内容。 (不知道你说的其他代码行是什么意思,对不起)
  • 好的!我进行了编辑,现在我遇到了另一个错误。它现在显示Failed prop type: Invalid prop 'children' of type 'array' supplied to 'MuiThemeProvider', expected a single ReactElement. 它包含在MuiThemeProvider 中,所以我不确定问题出在哪里。编辑*也会出现这个错误:Invariant Violation: MuiThemeProvider.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
  • 这意味着 MuiThemeProvider 想要只有一个孩子,但你给了它 2 AppBarDrawer。将 Appbar 和抽屉放在一个 div 中
  • 哇哦!它有效 :) 更重要的是,我了解发生了什么以及它是如何解决的。先生,我非常感谢您!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-21
  • 2018-07-22
  • 2018-06-30
  • 2019-09-23
  • 2013-10-08
  • 2018-01-23
  • 2019-08-08
相关资源
最近更新 更多