React博客搜索仅能过滤橙色标签无法筛选整张卡片,代码缺什么逻辑?
问题核心原因
你当前的过滤逻辑仅作用于卡片内的标签列表,没有对完整的博客文章数组做全局筛选,同时渲染卡片时直接遍历了原始的props.data而非筛选后的结果,因此只能过滤显示的标签,无法隐藏不匹配的整张卡片。
具体修改步骤
- 移除冗余变量和状态:删除没用的
tags状态、filteredArticle变量,二者和整卡筛选逻辑无关 - 新增全字段匹配的文章过滤逻辑:覆盖你想要纳入搜索范围的所有字段(标题、副标题、标签、作者名等),任意字段匹配搜索关键词就保留该文章卡片
- 渲染卡片时遍历过滤后的文章数组,而非原始的
props.data - 可选:如果不需要在匹配时隐藏卡片内不匹配的标签,将
BlogContent组件内标签部分的filter逻辑移除,直接遍历所有标签即可
核心修改代码
状态与过滤逻辑部分
// 仅保留搜索关键词状态 const [search, setSearch] = useState(``); // 新增全字段文章过滤逻辑 const filteredArticles = props.data.filter(article => { const keyword = search.toLowerCase().trim(); // 空搜索默认返回所有文章 if (!keyword) return true; // 各字段匹配规则,可根据需求增减 const matchTitle = article.title.toLowerCase().includes(keyword); const matchSubtitle = article.subtitle?.toLowerCase().includes(keyword) ?? false; const matchTag = article.tags.some(tag => tag.toLowerCase().includes(keyword)); const matchAuthor = article.author.name.toLowerCase().includes(keyword); // 任意字段匹配即保留该卡片 return matchTitle || matchSubtitle || matchTag || matchAuthor; });
卡片渲染部分
将原来遍历props.data改为遍历过滤后的filteredArticles:
<Grid container spacing={isMd ? 4 : 2}> {filteredArticles.map((item, index) => ( <Grid item xs={12} key={index} data-aos="fade-up"> <CardProduct withShadow liftUp className={clsx( classes.cardProduct, index % 2 !== 0 ? classes.cardProductReverse : {}, )} mediaContent={ <BlogMediaContent {...item.cover} alt={item.title} /> } cardContent={ <BlogContent title={item.title} subtitle={item.subtitle} tags={item.tags} author={item.author} date={item.date} /> } /> </Grid> ))} </Grid>
可选:卡片内标签不过滤的修改
如果希望整卡匹配后展示所有标签,而非仅展示匹配的标签,将BlogContent组件内的标签渲染部分修改为:
<div className={classes.tags}> {props.tags.map((item, key) => ( <Typography variant="caption" color="primary" className={classes.tag} key={key} > {item} </Typography> ))} </div>
内容的提问来源于stack exchange,提问作者Ulrik Magaña
相关产品推荐
相关产品推荐

