gpt4 book ai didi

javascript - 点击Away 时关闭material-ui popper

转载 作者:行者123 更新时间:2023-12-02 22:05:27 41 4
gpt4 key购买 nike

我有一个 Material ui popper,当我使用 popper 外部单击时,我试图将其关闭ClickAwayListener,但我无法让它工作。我在弹出器周围添加了 ClickAwayListener,并尝试将其添加在弹出器中的内容周围,但没有任何效果。

我对 Material-ui 非常陌生,所以我对如何完成这件事有点迷失

这是我的代码

const Experiences = memo(
(props) => {
const { className } = props;
const classes = useStyles(props);

const [anchorEl, setAnchorEl] = React.useState(null);

const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};

// const open = Boolean(anchorEl);
const handleClickAway = () => {
setAnchorEl(false);
};

const experience = (img, title, id, popoverCategory) => (
<div
className="experience"
aria-describedby={id}
id={id}
onClick={handleClick}
onKeyDown={handleClick}
role="button"
tabIndex="0"
>
<img
data-sizes="auto"
className="lazyload"
data-src={img}
alt={title}
/>
<div className="experience-title">
<Typography
color="textSecondary"
variant="subtitle2"
className="highlight highlight1"
display="inline"
>
{ title }
</Typography>
</div>


<ClickAwayListener onClickAway={handleClickAway}>
<Popper
id={id}
open={anchorEl && anchorEl.id === id}
anchorEl={anchorEl}
className={clsx(classes[id])}
modifiers={{
flip: {
enabled: false,
},
}}
>
<Button >x</Button>
<div className={clsx(classes.paper)}>
{
popoverCategory.map(url => (

<img
key={id}
data-sizes="auto"
className="lazyload"
src={url}
alt={title}
/>
))
}
</div>
</Popper>

</ClickAwayListener>
</div>

);

最佳答案

您可以切换您的<Popper />组件可见性使用父组件本地状态中的变量并将其作为 prop 传递下来:

//dependencies
const { render } = ReactDOM,
{ useState } = React,
{ Popper, Button, Paper, ClickAwayListener } = MaterialUI

//custom popper
const MyPopper = ({isOpen,clickAwayHandler}) => (
<ClickAwayListener onClickAway={clickAwayHandler}>
<Popper open={isOpen}>
<Paper className="popper">There goes my custom popper</Paper>
</Popper>
</ClickAwayListener>
)

//main page
const MainPage = () => {
const [isOpen, setIsOpen] = useState(true),
clickAwayHandler = () => setIsOpen(false),
clickHandler = () => setIsOpen(true)
return (
<div>
<Button onClick={clickHandler}>Toggle pop-up</Button>
{
isOpen && <MyPopper {...{clickAwayHandler,isOpen}} />
}
</div>
)
}

//render
render (
<MainPage />,
document.getElementById('root')
)
.popper {
display: block;
position: relative;
top: 50px;
left: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script><div id="root"></div>

关于javascript - 点击Away 时关闭material-ui popper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59733592/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com