我有一个用Material UI构建的菜单组件。在菜单内单击复选框后,我想使菜单保持在同一位置。现在,它会关闭弹出窗口。
我在handleChange函数上尝试过event.stopPropagation()和event.preventDefault(),该函数无法管理复选框的onChange事件。
这是我的菜单的简化视图:
<Menu
anchorEl={anchorEl}
id={menuId}
keepMounted
anchorOrigin={{
vertical: "bottom",
horizontal: "center"
}}
transformOrigin={{
vertical: "top",
horizontal: "center"
}}
open={isMenuOpen}
onClose={handleMenuClose}
style={{ marginTop: "1.56em" }}
>
<FormControl component="fieldset" className={classes.formControl}>
<FormGroup>
{checkboxes.map(checkbox => {
return (
<FormControlLabel
key={checkbox.term}
control={
<Checkbox
checked={checkbox.checked}
onChange={handleChange(checkbox.term)}
value={checkbox.term}
color="primary"
className={classes.root}
/>
}
label={checkbox.label}
/>
);
})}
</FormGroup>
</FormControl>
</Menu>
handleChange函数是:
const handleChange = value => event => {
setFilters(rest => {
return { ...rest, contract: { ...filters.contract, [value]: event.target.checked } };
});
};
isMenuOpen指的是:
const [anchorEl, setAnchorEl] = useState(null);
const isMenuOpen = Boolean(anchorEl);
和handleMenuClose指的是:
const handleMenuClose = () => {
setAnchorEl(null);
};
上面我说简化视图是因为组件的层次结构实际上是这样的:
|
- TopLevelController component (hosts the state for the whole components tree and passes it down; hosts the setFilters function)
|
-- SearchAndFilter component (hosts my App bar and a bunch of MenuSection components)
|
--- MenuSection components (hosts the <Menu> component above and a bunch of sub components for each popover)
|
---- SubMenu component (hosts the <FormControl> component above)
-
因此,在单击包含其的复选框后,我需要SubMenu组件(弹出窗口)保持打开状态,但这并不是这种情况。
我的最佳猜测是,顶级setFilters函数使整个组件树重新呈现,并因此在每次刷新后将子组件的anchorEl状态初始化为null。
有什么办法优雅地处理这个问题吗?谢谢:)