我正在尝试使用ASP.net core 2.1
,Typescript 3.2.1
,material-ui 3.8.3
和React 16.7.0
来实现一个简单的菜单。当我运行应用程序时,它崩溃并显示useState
,错误为TypeError: react__WEBPACK_IMPORTED_MODULE_1___default.a.useState is not a function
。
import React from 'react';
import { Link } from 'react-router-dom';
import { withStyles } from '@material-ui/core/styles'
import IconButton from '@material-ui/core/IconButton'
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import MenuIcon from '@material-ui/icons/Menu'
function TopbarMenu(props: any) {
const { classes } = props
const [anchorEl, setAnchorEl] = React.useState(null); // Crashes here. Compiled line becomes: var _React$useState = react__WEBPACK_IMPORTED_MODULE_1___default.a.useState(null),
function handleClick(event: any) {
console.log(event.currentTarget)
setAnchorEl(event.currentTarget);
}
function handleClose() {
setAnchorEl(null);
}
return (
<div>
<IconButton onClick={handleClick} className={classes.menuButton} color="inherit" aria-label="Menu">
<MenuIcon />
</IconButton>
<Menu id="simple-menu" anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={handleClose}>
<MenuItem onClick={handleClick}><Link to={'/orderform'}>Orderform</Link></MenuItem>
<MenuItem onClick={handleClick}><Link to={'/products'}>Products</Link></MenuItem>
<MenuItem onClick={handleClick}><Link to={'/customers'}>Customers</Link></MenuItem>
<MenuItem onClick={handleClick}><Link to={'/licenses'}>Expiring Licenses</Link></MenuItem>
</Menu>
</div>
);
}
const styles = {
menuButton: {
marginLeft: -12,
marginRight: 20,
},
}
export default withStyles(styles)(TopbarMenu)
我在这里想念什么?
我正在跟踪此处找到的Material-ui文档:https://material-ui.com/demos/menus/#simple-menu
答案 0 :(得分:1)
修改
旁注: 始终在React函数的顶层使用挂钩。
//Not that bad
const { classes } = props
const [anchorEl, setAnchorEl] = React.useState(null);
//Preferably (in my opinion)
const [anchorEl, setAnchorEl] = React.useState(null);
const { classes } = props
答案
React Hooks可从React 16.7.0-alpha reactconf2018获得。现在在React v16.8.0-alpha.0.
中可用答案 1 :(得分:0)
试试这个
const [anchorEl, setAnchorEl] = React.useState<Element|null>(null);