我怎么了,你能告诉我2怎么办吗?
我正在创建一个需要钩子替换状态的网站。我在我的index.js上。错误在于菜单内div内的onClicks。菜单来自Material-UI
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
export default function SimpleMenu() {
const [ anchorEl, setAnchorEl ] = React.useState<null | HTMLElement>(null);
const [ language, setLanguage ] = useState('English');
const languages = [ 'English', 'Chinese ( Simplified )', 'Chinese ( Traditional )' ];
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = (word: string) => {
setLanguage(word);
};
return (
<div>
<Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick}>
Open Menu
</Button>
<Menu id="simple-menu" anchorEl={anchorEl} keepMounted open={Boolean(anchorEl)} onClose={handleClose}>
<div onClick={handleClose(languages[0])}>{languages[0]}</div>
<div onClick={handleClose(languages[1])}>{languages[1]}</div>
<div onClick={handleClose(languages[2])}>{languages[2]}</div>
</Menu>
</div>
);
}
----------
error:
```Type 'void' is not assignable to type '(event: MouseEvent<HTMLDivElement, MouseEvent>) => void'.```
can u please help me?
( bottom is gibberish )
答案 0 :(得分:1)
将onClick={handleClose(languages[0])}
更改为这样的箭头功能
onClick={() => handleClose(languages[0])}
或更改handleClose函数
const handleClose = () => (word: string) => {
setLanguage(word);
};
答案 1 :(得分:1)
嘿,希望这能解决您的问题: 首先像这样在按钮上编写 onClick :
<Button
aria-controls="simple-menu"
aria-haspopup="true"
onClick={() => handleClick(event as MouseEvent)}
>
Open Menu
</Button>
然后像这样写你的句柄点击:
const handleClick = (event: MouseEvent) => {
setAnchorEl(event.currentTarget);
};
可能不是最好的解决方案,但我认为它可以解决您的问题:)