[英]Why the initial loading state is set to true while using useState?
[英]Unexpected keyword 'true' while using `useState` in react?
在这里,当用户单击它时,我尝试将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);
错误在:
[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.