在材料ui中将AppBar与抽屉结合使用

时间:2018-02-14 06:25:04

标签: javascript reactjs material-ui

我有一个AppBar组件,我想将它与抽屉结合,这是AppBar代码:

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "material-ui/styles";
import AppBar from "material-ui/AppBar";
import Toolbar from "material-ui/Toolbar";
import Typography from "material-ui/Typography";
import Button from "material-ui/Button";
import IconButton from "material-ui/IconButton";
import MenuIcon from "material-ui-icons/Menu";
import TemporaryDrawer from "./Drawer";

const styles = {
  root: {
    width: "100%"
  },
  flex: {
    flex: 1
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20
  },
};

function ButtonAppBar(props) {
  const { classes } = props;
  return (
    <div className={classes.root}>
        <TemporaryDrawer/>
      <AppBar position="static">
        <Toolbar>
          <IconButton className={classes.menuButton} color="inherit" aria-label="Menu">
            <MenuIcon />
          </IconButton>
          <Typography variant="title" color="inherit" className={classes.flex}>
            Title
          </Typography>
          <Button color="inherit">Drawer</Button>
        </Toolbar>
      </AppBar>
    </div>
  );
}

ButtonAppBar.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(ButtonAppBar);

目前我正在使用material-ui v1.0.0-beta.33,我想要的是在点击我在AppBar中的Button时打开左侧的抽屉,但我不知道如何做到这一点。

我会很感激你的帮助。

1 个答案:

答案 0 :(得分:4)

如果我理解正确你可以这样做 - 存储布尔值,表示抽屉是在组件状态下打开的:

state = { drawerIsOpen: false }

当用户点击按钮时,您将更改它:

  handleDrawerOpen = () => {
    this.setState({ drawerIsOpen: true });
  };

您的render方法应如下所示:

render() {
  const { classes } = this.props;

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton className={classes.menuButton} color="inherit" aria-label="Menu">
            <MenuIcon />
          </IconButton>
          <Typography variant="title" color="inherit" className={classes.flex}>
            Title
        </Typography>
          <Button onClick={this.handleDrawerOpen} color="inherit">Drawer</Button>
        </Toolbar>
      </AppBar>
      <Drawer
        variant="persistent"
        classes={{
          paper: classes.drawerPaper,
        }}
        open={this.state.drawerIsOpen}
      >
        <div className={classes.drawerHeader}>
          <IconButton onClick={this.handleDrawerClose}>
            <ChevronLeftIcon />
          </IconButton>
        </div>
        <div className={classes.drawerInner}>
          <p>drawer content</p>
        </div>
      </Drawer>
    </div>
  );
}

检查this simplified demo(请参阅demo.js文件)。