问题描述
import { Modal } from "antd";
function Profile(){
const [visible,setVisible] = useState(false);
return(
<>
{myposts.map((mypost,index) => {
return (
<>
<img
key={index}
className="item"
onClick={() => {
setVisible(true);
}}
src={`http://localhost:5000/uploads/${mypost.photo}`}
/>
{visible && (
<Modal
title="Basic Modal"
visible={visible}
onOk={setVisible(false)}
onCancel={setVisible(false)}
>
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</Modal>
)}
</>
);
})}
</>
)}
这是我代码的总结。我认为当我单击图像时,它应该是模态的。但是,它没有任何作用。我不知道哪一部分错了。 (模态部分现在有一些奇怪的内容。看到模态后,我将对此部分进行更改。)
解决方法
尝试将模态放置在mypost地图之外,也许这就是为什么模态不会显示的原因。所选图像的src路径可能需要其他状态。
import { Modal } from "antd";
function Profile() {
const [visible,setVisible] = useState(false);
const [selectedImgSrc,setSelectedImgSrc] = useState("");
const imgClick = (imgSrc) => {
setSelectedImgSrc(imgSrc);
setVisible(true);
};
return (
<>
{myposts.map((mypost,index) => {
return (
<>
<img
key={index}
className="item"
onClick={() => {
imgClick(`http://localhost:5000/uploads/${mypost.photo}`);
}}
src={`http://localhost:5000/uploads/${mypost.photo}`}
/>
</>
);
})}
<Modal
title="Basic Modal"
visible={visible}
onOk={() => setVisible(false)}
onCancel={() => setVisible(false)}
>
<img src={selectedImgSrc} />
</Modal>
</>
);
}
,
问题似乎在您的代码中。
<Modal
title="Basic Modal"
visible={visible}
onOk={setVisible(false)}
onCancel={setVisible(false)}
>
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</Modal>
onOk={setVisible(false)}
onCancel={setVisible(false)}
问题是这些行。
单击图像时,它将打开您的模态,但是当要渲染模态时,这些行会将可见状态设置为false
。因此,该模式将很快从DOM中删除。
这就是为什么您看不到点击图片的方式。
请尝试这个。
onOk={() => setVisible(false)}
onCancel={() => setVisible(false)}
您应该传递onOk和onCancel道具的函数。