我有一个组件体验,可以创建6个体验,每个体验都有一个带有图像的弹出窗口。如果要单击另一个弹出器,我希望能够关闭打开的弹出器,但是我不知道如何更改代码以执行此操作。
这是我的组成部分
*/const Experiences = memo(
(props) => {
const { className } = props;
const classes = useStyles(props);
const [poperOpen, setPoperOpen] = React.useState([]); // array of popers states
const [justChange, setJustChange] = useState(false); // array of popers states
// one handle click for open/close
const handleClick = (e, _id, _open) => {
const idx = poperOpen.findIndex(x => x.id === _id);
const a = poperOpen;
if (idx > -1) {
a.splice(idx, 1);
}
a.push({ id: _id, open: _open, anchorEl: e.currentTarget });
setPoperOpen(a);
setJustChange(!justChange);
};
const experience = (img, title, id, popoverCategory) => (
<div>
<div
className="experience"
aria-describedby={id}
id={id}
onClick={e => handleClick(e, id, true)}
onKeyDown={e => handleClick(e, id, true)}
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>
</div>
<Popper
id={id}
open={poperOpen.findIndex(x => x.id === id) > -1 && poperOpen.find(x => x.id === id).open}
anchorEl={poperOpen.findIndex(x => x.id === id) > -1
? poperOpen.find(x => x.id === id).anchorEl : undefined}
className={clsx(classes[id])}
modifiers={{
flip: {
enabled: false,
},
}}
>
<Button onClick={e => handleClick(e, id, false)}>x</Button>
<div className={clsx(classes.paper)}>
{
popoverCategory.map(url => (
<img
key={id}
data-sizes="auto"
className="lazyload"
src={url}
alt={title}
/>
))
}
</div>
</Popper>
</div>
);
我需要更改
const [poperOpen, setPoperOpen] = React.useState([]);
我想这样的事情
const [poperOpen,setPoperOpen] = React.useState(null);
但是当我这样做时,我会得到一个错误
TypeError:无法读取null的属性'findIndex'
答案 0 :(得分:1)
正确的方法是更改poperOpen
数组的先前状态,而不是像使用代码a
那样在代码中进行修改时直接修改代码,{ 1}}的参考。
在这里找到poperOpen
的可行解决方案:
handleClick
希望对您有帮助!
答案 1 :(得分:0)
您可以手动关闭handleClick方法中的所有Poppers,然后只打开正确的Poppers。
const handleClick = (e, _id, _open) => {
const idx = poperOpen.findIndex(x => x.id === _id);
const a = poperOpen;
a.forEach((part, index) => {
a[index].open = false;
});
...
};