[英]How to render multiple modals in react?
I need to render multiple modals but the number of modals are not fixed and depend on property audios
of the object coming in. I'm currently using the mui modal我需要渲染多个模态,但模态的数量不固定,取决于传入的 object 的属性
audios
。我目前正在使用 mui 模态
This is the variables used:这是使用的变量:
const [open, setOpen] = useState(false);
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
And this is how I attempt to render the modals.这就是我尝试渲染模态的方式。 Currently, the modal that opens after clicking 'view' only shows the last value in
audios
no matter which 'View' button I click on目前,无论我点击哪个“查看”按钮,单击“查看”后打开的模态仅显示
audios
中的最后一个值
{audios.map((a) => (
<Grid item container justifyContent="flex-end">
<Button
onClick={handleOpen}
sx={{
color: 'blue',
marginTop: '0.6rem',
}}
>
View
</Button>
<Modal
open={open}
onClose={handleClose}
>
<Box
sx={{
position: 'absolute' as 'absolute',
top: '50%',
left: '50%',
p: 4,
}}
>
<Typography color='white'>{a.name}</Typography>
</Box>
</Modal>
</Grid>
))}
Is there way to have separate state for open and close for each modal?有没有办法为每个模态打开和关闭单独的 state?
I think u should put the 'open' state in the Modal component, by this way every Modal have their own state.我认为你应该将“开放”state 放在模态组件中,这样每个模态都有自己的 state。
const MyModalandButton=()=>{
const [open, setOpen] = useState(false);
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
return <>
<Button
onClick={handleOpen}
sx={{
color: 'blue',
marginTop: '0.6rem',
}}
>
View
</Button>
<Modal
open={open}
onClose={handleClose}
> </>
}
maybe just like this也许就像这样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.