簡體   English   中英

在反應中使用`useState`時出現意外的關鍵字'true'?

[英]Unexpected keyword 'true' while using `useState` in react?

在這里,當用戶單擊它時,我嘗試將MUIDraweropen屬性設置為true ,但是在設置state時,我收到錯誤消息“意外關鍵字 '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);

錯誤在:

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

首先,您忘記了 useState 掛鈎中的const關鍵字。

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

並且 toggleDrawer 必須是 function 你可以這樣做:

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

或者

function toggleDrawer(){
   setState(true)
}

如果需要,可以在 onClick 內部制作 function:

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

最后,如果您想在再次單擊它時使其為假:

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

在最后一種情況下setState(!state)將允許您保存 state 的反面。

然后,對於您進行的每次單擊,state 值將變為與先前值相反的值。

嘗試將toggleDrawer聲明為 function,如下所示:

const toggleDrawer = () => setState(true)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM