抽屉器的实现AppBar with Material-UI + React{不能读取属性'的零}

Implementing a Drawer & AppBar with Material-UI + React {Cannot read property 'open' of null}

本文关键字:属性 读取 不能读 不能 的零 React 实现 AppBar Material-UI with      更新时间:2023-09-26

所以我试图使用React &Material-UI创建一个应用程序,所以我设法让AppBar启动并运行,但我有一些问题让抽屉工作。

我一直得到一个error: cannot read property open of null,并试图找出问题是什么,没有成功。我在Stack上找到了关于这个确切问题的2个帖子,他们都没有一个能够解决我的问题的答案

无法使用Appbar + Drawer (Material UI + ReactJS)

Uncaught TypeError: Cannot read property 'open'AppBar +抽屉组件(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>
  }

(代码片段不应该运行,只是显示我的相关代码)

我想也许将this绑定到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()