问题描述
我正在使用带有反应的离子框架。我想使用 ion-searchbar 组件根据标题过滤卡片。我已经使用过,但坚持如何在反应中向这个搜索栏组件添加功能。请告诉我如何在反应中使用 ionSearchabar 过滤离子卡。我写的代码如下:
import {IonCardSubtitle,IonCardContent,IonIcon,IonCardTitle,IonCard,IonCol,IonRow,IonBackButton,IonContent,IonHeader,IonPage,IonTitle,IonToolbar,IonLabel,IonSearchbar,IonFooter,} from'@ionic/react';
import {
chevronForwardOutline,arrowForwardOutline,homeOutline
} from 'ionicons/icons';
import React,{ useState } from 'react';
import usa from '../assets/writing-screen-icons/img.svg';
const countries =[
{
id:1,title: "usa",subtitle: "country",route: "/country/usa",thumbnail: usa
},{
id:2,title: "pakistan",route: "/country/pk",thumbnail: usa
},{
id:3,title: "france",route: "/country/france",thumbnail: usa
},id:4,title: "canada",route: "/country/canada",id:5,title: "uk",route: "/country/uk",thumbnail: usa
}
];
const Country React.FC = () => {
const [searchText,setSearchText] = useState('');
const showCardCols=(topic:any,index:any)=>{
return(
<IonCol size="12" key="index">
<IonCard mode="ios" routerLink={topic.route}>
<img src={topic.thumbnail}></img>
<IonCardSubtitle>{topic.subtitle}</IonCardSubtitle>
<IonCardTitle>{topic.title}</IonCardTitle>
<IonIcon icon={chevronForwardOutline} />
</IonCard>
</IonCol>
);
}
return (
<IonPage>
<IonContent fullscreen>
<h1>Countries</h1>
<IonSearchbar mode="ios" value={searchText} onIonChange={e => setSearchText(e.detail.value!)}></IonSearchbar>
<IonGrid>
<IonRow>
{writingTopics.map(showCardCols)}
</IonRow>
</IonGrid>
</IonContent>
</IonPage>
);
};
export default Country;
解决方法
您需要向 showCardCols
函数添加一些过滤器逻辑。实际上你的函数映射数组并返回它而不做任何操作。
例如,您可以从 render
调用函数:
<IonRow>
{showCardCols()}
</IonRow>
然后,从您的函数中选择要显示的卡片:
const showCardCols = () => {
return(
countries.forEach((element,index) => { // <-- Iterate over your array
if(element.title.indexOf(searchText) !== -1){ // <-- Check if title of the country matches your search text
<IonCol size="12" key="index">
<IonCard mode="ios" routerLink={element.route}>
<img src={element.thumbnail}></img>
<IonCardSubtitle>{element.subtitle}</IonCardSubtitle>
<IonCardTitle>{element.title}</IonCardTitle>
<IonIcon icon={chevronForwardOutline} />
</IonCard>
</IonCol>
}
})
);
}