点击按钮时React Ionic Modal未关闭



我使用了Ionic文档关于使用布尔状态来确定何时打开或关闭模态的指南。当点击卡片时,它会将状态设置为打开模式,但当按下关闭图标时,它不会将状态更改回false或关闭模式。如果我创建一个单独的组件来处理这种行为,这可能吗?

import { useState } from "react";
import {
IonCard,
IonGrid,
IonCardHeader,
IonCardTitle,
IonCardSubtitle,
IonText,
IonCardContent,
IonImg,
IonRow,
IonCol,
IonAvatar,
IonModal,
IonHeader,
IonToolbar,
IonIcon,
IonTitle,
} from "@ionic/react";
import { closeOutline, closeSharp } from "ionicons/icons";
import "./UserCard.css";
type UserCardProps = {
id: number;
name: string;
icon: string;
email: string;
country: string;
image: string;
description: string;
};
export const UserCard = (props: UserCardProps) => {
const [detailModal, setDetailModal] = useState({ isOpen: false });
const handleClose = () => {
console.log(`Value before setDetailModal: ${detailModal.isOpen}`);
setDetailModal({ isOpen: false });
console.log(`Value after setDetailModal: ${detailModal.isOpen}`);
};
return (
<IonCard
onClick={() => setDetailModal({ isOpen: true })}
id={`${props.name}Modal`}
>
{/* When card clicked, open modal */}
<IonModal isOpen={detailModal.isOpen}>
<IonHeader>
<IonToolbar mode="ios" className="ion-padding">
<IonIcon
slot="start"
ios={closeOutline}
md={closeSharp}
onClick={handleClose} // Modal currently does not close when clicked
/>
<IonTitle className="ionTextCenter">{props.name}</IonTitle>
</IonToolbar>
</IonHeader>
{/* Detailed Modal component */}
<IonCard id="detailModal">
<IonCardHeader>
<IonImg src={props.image} />
<IonGrid>
<IonRow>
<IonCol size="3">
<IonAvatar>
<img src={props.icon} />
</IonAvatar>
</IonCol>
<IonCol size="9">
<IonCardTitle>{props.name}</IonCardTitle>
<IonCardSubtitle>{props.email}</IonCardSubtitle>
</IonCol>
</IonRow>
</IonGrid>
</IonCardHeader>
<IonCardContent>
<IonText>
<p>This photo was taken in: {props.country}</p>
</IonText>
</IonCardContent>
</IonCard>
</IonModal>
{/* Detailed Modal component end */}
{/* Card component */}
<IonCardHeader className="card-header">
<IonGrid>
<IonRow>
<IonCol size="3">
<IonAvatar>
<img src={props.icon} />
</IonAvatar>
</IonCol>
<IonCol size="9">
<IonCardTitle>{props.name}</IonCardTitle>
<IonCardSubtitle>{props.email}</IonCardSubtitle>
</IonCol>
</IonRow>
</IonGrid>
</IonCardHeader>
<IonCardContent>
<img src={props.image} className="center-img" />
<IonText className="ion-text-center ion-margin">
<h2 className="subheading">{props.country}</h2>
</IonText>
<IonImg className="character-img"></IonImg>
{props.description}
</IonCardContent>
{/* Card component end */}
</IonCard>
);
};

您可以尝试使用带关闭句柄的箭头函数吗?

结账https://reactjs.org/docs/faq-functions.html

<IonIcon
slot="start"
ios={closeOutline}
md={closeSharp}
onClick={() => handleClose()} 
/>

也请查看此链接!https://reactjs.org/docs/handling-events.html

最新更新