什么是Uncaught TypeError:无法读取AppBar + Drawer组件的未定义属性'open'(ReactJS + Material-UI)?

时间:2016-05-21 00:04:12

标签: javascript reactjs drawer material-ui appbar

我试图从Material-UI框架获取AppBar左侧的导航,默认汉堡图标(http://www.material-ui.com/#/components/app-bar),以便在单击(http://www.material-ui.com/#/components/drawer)时滑动打开抽屉组件。但是一旦点击,我就会收到以下错误,我无法弄明白:

未捕获的TypeError:无法读取未定义的属性“open”

非常感谢任何有关它的见解或指导。先感谢您。

import React, { Component } from 'react'
import { Drawer, AppBar, MenuItem} from 'material-ui'
import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme'
import getMuiTheme from 'material-ui/styles/getMuiTheme'
import { Route, Router } from 'react-router'



export default class Main extends Component  {

  constructor(props, context){
    super(props, context);
    this.state = {open:false};
  }

  getChildContext() {
    return {muiTheme: getMuiTheme(baseTheme)};
  }

  handleToggle() {
    this.setState({open: !this.state.open});
   }

        render() {
            return (
                <div>
                <AppBar   
                  isInitiallyOpen={true} 
                  onLeftIconButtonTouchTap={this.handleToggle}        
                  onLeftIconButtonClick={this.handleToggle} 
                />

                <Drawer
                  docked={false}
                  open={this.state.open}>
                  <MenuItem>Menu Item 1</MenuItem>
                  <MenuItem>Menu Item 2</MenuItem>
                  <MenuItem>Menu Item 3</MenuItem>
                </Drawer>
                </div>
            );
        }
    }

export default Main;

1 个答案:

答案 0 :(得分:0)

您还可以使函数组件代替类componnet,这将使您的组件清晰易读-


import React, { useState } from 'react'
import { Drawer, AppBar, MenuItem } from 'material-ui'
import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme'
import getMuiTheme from 'material-ui/styles/getMuiTheme'
import { Route, Router } from 'react-router'



export default function Main(props) {

    let [open, setOpen] = useState(false);

    let handleToggle = () => {
        setOpen(!open);
    }

    return (
        <div>
            <AppBar
                isInitiallyOpen={true}
                onLeftIconButtonTouchTap={handleToggle}
                onLeftIconButtonClick={handleToggle}
            />

            <Drawer
                docked={false}
                open={open}>
                <MenuItem>Menu Item 1</MenuItem>
                <MenuItem>Menu Item 2</MenuItem>
                <MenuItem>Menu Item 3</MenuItem>
            </Drawer>
        </div>
    );
}