我有一个组件体验,可以创建 6 个体验,每个体验都有一个带有图像的 popper。我希望能够关闭在单击另一个弹出器时打开的弹出器,但我不知道如何更改代码来执行此操作。
这是我的组件
*/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);
但是当我这样做时出现错误
类型错误:无法读取 null 的属性“findIndex”
最佳答案
正确的方法是poperOpen
数组改变之前的状态,而不是像使用a
时在代码中那样直接修改变量,从技术上讲,它仍然是 poperOpen
的引用。
在这里找到handleClick
可能的工作解决方案:
const handleClick = (e, _id, _open) => {
setPoperOpen(prevArray => {
const idx = prevArray.findIndex(x => x.id === _id);
const a = [...prevArray];
if (idx > -1) {
a.splice(idx, 1);
}
a.push({ id: _id, open: _open, anchorEl: e.currentTarget });
return a;
});
setJustChange(!justChange);
};
希望对您有所帮助!
关于javascript - 我有很多弹出器,希望打开的那个在另一个打开时关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59741347/