[英]Unexpected keyword 'true' while using `useState` in react?
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' "在这里,当用户单击它时,我尝试将
MUIDrawer
的open
属性设置为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);
The errors are in:错误在:
[state, setState] = useState(false);
const toggleDrawer = {setState(true)}
First you forgot the const
keyword in the useState hook.首先,您忘记了 useState 挂钩中的
const
关键字。
const [state, setState] = useState(false);
And the toggleDrawer must be a function you can do that like the following:并且 toggleDrawer 必须是 function 你可以这样做:
const toggleDrawer = () => {setState(true)}
or或者
function toggleDrawer(){
setState(true)
}
If you want, you can make the function inside the onClick:如果需要,可以在 onClick 内部制作 function:
<IconButton
style={{ position: "absolute", right: "0" }}
onClick={()=>{setState(true)}}
>
And finally if you want to make it false when you click it again:最后,如果您想在再次单击它时使其为假:
<IconButton
style={{ position: "absolute", right: "0" }}
onClick={()=>{setState(!state)}}
>
In this last case setState(!state)
will allow you to save the opposite of state.在最后一种情况下
setState(!state)
将允许您保存 state 的反面。
Then, for each click you make, the state value will change to the opposite of the previous value.然后,对于您进行的每次单击,state 值将变为与先前值相反的值。
Try declaring toggleDrawer
as a function, like this:尝试将
toggleDrawer
声明为 function,如下所示:
const toggleDrawer = () => setState(true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.