2

Here i am trying to set the open prop of the MUIDrawer to true when the user clicks it but while setting the state i am getting an error "Unexpected keyword 'true' "

import React, { useState } from "react";
import { withRouter } from "react-router-dom";
import {
  Drawer as MUIDrawer,
  ListItem,
  List,
  ListItemIcon,
  ListItemText,
  AppBar,
  Toolbar,
  IconButton
} from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import InboxIcon from "@material-ui/icons/MoveToInbox";
import MailIcon from "@material-ui/icons/Mail";
import MenuIcon from "@material-ui/icons/Menu";

const useStyles = makeStyles({
  drawer: {
    width: "190px"
  }
});

const Drawer = props => {
  const { history } = props;
  const classes = useStyles();
  const itemsList = [
    {
      text: "Home",
      icon: <InboxIcon />,
      onClick: () => history.push("/")
    },
    {
      text: "About",
      icon: <MailIcon />,
      onClick: () => history.push("/about")
    },
    {
      text: "Contact",
      icon: <MailIcon />,
      onClick: () => history.push("/contact")
    }
  ];

  

  [state, setState] = useState(false);
  
  const toggleDrawer = {setState(true)}

  return (
    <>
      <AppBar>
        <Toolbar>
          <IconButton
            style={{ position: "absolute", right: "0" }}
            onClick={toggleDrawer}
          >
            <MenuIcon />
          </IconButton>
        </Toolbar>
      </AppBar>
      <MUIDrawer
        className={classes.drawer}
        open={state}
      >
        <List>
          {itemsList.map((item, index) => {
            const { text, icon, onClick } = item;
            return (
              <ListItem button key={text} onClick={onClick}>
                {icon && <ListItemIcon>{icon}</ListItemIcon>}
                <ListItemText primary={text} />
              </ListItem>
            );
          })}
        </List>
      </MUIDrawer>
    </>
  );
};

export default withRouter(Drawer);

4

2 回答 2

4

错误在:

  [state, setState] = useState(false);
  
  const toggleDrawer = {setState(true)}

首先,您忘记了constuseState 挂钩中的关键字。

  const [state, setState] = useState(false);

并且 toggleDrawer 必须是一个函数,你可以这样做:

const toggleDrawer = () => {setState(true)}

或者

function toggleDrawer(){
   setState(true)
}

如果需要,可以在 onClick 中创建函数:

<IconButton
   style={{ position: "absolute", right: "0" }}
   onClick={()=>{setState(true)}}
>

最后,如果您想在再次单击它时使其为假:

<IconButton
   style={{ position: "absolute", right: "0" }}
   onClick={()=>{setState(!state)}}
>

在这最后一种情况下setState(!state),将允许您保存相反的状态。

然后,对于您进行的每次单击,状态值将更改为与先前值相反的值。

于 2020-07-14T20:25:40.503 回答
1

尝试声明toggleDrawer为函数,如下所示:

const toggleDrawer = () => setState(true)

于 2020-07-14T20:13:58.990 回答