问题描述
从 API 请求中,我得到了如下所示的数据数组(我得到了 100 个元素,但在这里我只显示了 2 个):
data: Array(2)
0: {cardId: 270,name: "Basic card",type: "type1"}
1: {cardId: 345,name: "Special card",type: "type2"}
我在我的应用中使用 map()
方法显示它们。
每个数组元素都通过 <IonCard>
显示在应用程序中。卡片名称在 <IonCardTitle>
中,卡片类型在 <IonCardContent>
中。
目前,在我的实际实现中,当我点击特定的 <IonCardTitle>
时,所有元素的内容都会被打开。
我的目标是:点击特定元素标题时,仅打开该元素的内容。 我怎样才能做到这一点?
任何帮助将不胜感激。
卡片页面:
import {
IonContent,IonPage,IonCard,IonCardHeader,IonCardTitle,IonCardContent,IonItem,IonLabel,IonIcon,} from "@ionic/react";
import React,{ useEffect,useRef,useState } from "react";
import { Http} from "@capacitor-community/http";
const Cards: React.FC = () => {
const [cards,setCards] = useState([]);
const [content,setContent] = useState([]);
const [showContent,setShowContent] = useState([]);
const mounted = useRef(true);
useEffect(() => {
mounted.current = true;
const options = {
url: "xxx/cards",headers: {
Accept: "application/json","Content-Type": "application/json",},};
Http.request({ ...options,method: "GET" }).then(
(response) => {
if (mounted.current) {
setCards(response.data);
}
},(error) => {
const _content =
(error.response && error.response.data) ||
error.message ||
error.toString();
setContent(_content);
}
);
return () => {
mounted.current = false;
};
},[]);
return (
<React.Fragment>
<IonPage className="ion-page" id="main-content">
<IonContent className="ion-padding">
{cards &&
cards.map((card: any) => (
<IonCard key={card.cardId}>
<IonCardHeader>
<IonCardTitle>
<IonItem
button
onClick={() => {
setShowContent(true);
if (showContent === true) {
setShowContent(false);
}
}}
>
<IonIcon
slot="end"
icon={showDetails ? arrowDown : arrowForward}
></IonIcon>
<IonLabel>
<b>{card.name}</b>
</IonLabel>
</IonItem>
</IonCardTitle>
</IonCardHeader>
{showContent && (
<IonCardContent>
<p>Card Type: {card.type}</p>
</div>
</IonCardContent>
)}
</IonCard>
))}
</IonContent>
</IonPage>
</React.Fragment>
);
};
export default Cards;
解决方法
-
首先,更新初始状态:
const [showContent,setShowContent] = useState(null);
-
然后,更新 onClick:
onClick={() => { setShowContent(card.cardId); if (showContent === card.cardId) { setShowContent(null); } }}
-
最后,更新条件渲染内容:
{showContent === card.cardId && (<IonCardContent>...</IonCardContent>)