如果选择Popper选项,则TextField上的Material UI Popper如何保持Popper处于打开状态 [英] Material UI Popper over TextField how to keep popper open if the popper options are selected
问题描述
我正在使用React Material UI,并且我有一个Textfield,如果我专注于它,它将部署带有简单Menu的Popper.如果Textfield失去焦点,则Popper会自行关闭.问题是我需要在不关闭 Popper 的情况下从菜单中选择任何选项,但是当我这样做时,Textfield 失去了焦点.我需要的是仅在我在文本字段"或菜单"之外单击时才打开Popper.
I am using React Material UI, and I have a Textfield which if I focus on it will deploy a Popper with a simple Menu. If the Textfield loses the focus then the Popper closes itself. The thing is I need to select any option from the menu without close the Popper, but when I do that the Textfield loses the focus. What I need is to keep the Popper on only if I click outside of the Textfield or the Menu.
codesandbox 上的所有内容.
我尝试过:
const selected = prop => {
console.log(prop);
}
...
<Paper elevation={3} className={classes.paper}>
<MenuList>
<MenuItem onClick={() => selected('first')}>
First Option
</MenuItem>
<MenuItem onClick={() => selected('next')}>
Next Option
</MenuItem>
<MenuItem onClick={() => selected('last')}>
And Last Option
</MenuItem>
</MenuList>
</Paper>
</Popper>
还尝试了使用 ClickAwayListener
包装两个组件,即TextField和Popper:
Also tried with ClickAwayListener
wrapping both components, the TextField and the Popper:
<ClickAwayListener onClickAway={blur}>
<>
<TextField ... />
<Popper ...>
...
</Popper>
</>
</ClickAwayListener>
两次均未成功...我该如何实现?
Unsuccessfully both times... How can I achieve this?
推荐答案
我认为最好使用自动完成功能来实现此目的,但是由于OP请求了另一种解决方案-这是另一种选择:
I think it's best to implement this using the Autocomplete, but since the OP requested another solution - here is another option:
一旦模糊-检查导致模糊的元素.如果该元素是波普尔中的项目之一,请不要模糊:
Once blur - check the element that caused the blur. If that element is one of the items in the popper - don't blur:
if (e.relatedTarget && e.relatedTarget.classList.contains("MuiListItem-root")) {
return;
}
完全模糊功能将如下所示:
The full blur function will look like this:
const blur = (e) => {
if (e.relatedTarget && e.relatedTarget.classList.contains("MuiListItem-root")) {
e.target.focus();
return;
}
setAnchorEl(null);
};
这篇关于如果选择Popper选项,则TextField上的Material UI Popper如何保持Popper处于打开状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!